"use client";

import React, {
    createContext,
    FC,
    useContext,
    useEffect,
    useState,
} from "react";
import { useMutation, UseMutationResult } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import useStatusesList from "@/hooks/useStatusesList";
import { useStatusesOperations } from "@/hooks/useStatusesOperations";
import {
    HttpValidationError,
    Options,
    StatusSchema,
    UpdateStatusData,
    UpdateStatusResponse,
    UpdateStatusSchema,
} from "@/lib/client";
import { updateStatusMutation } from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

type StatusesContextState = {
    statuses: StatusSchema[];
    setStatuses: React.Dispatch<React.SetStateAction<StatusSchema[]>>;
    updateStatus: UseMutationResult<
        UpdateStatusResponse,
        AxiosError<HttpValidationError>,
        Options<UpdateStatusData>
    >;
    refetchStatuses: () => void;
    onCreateStatus: (name: string) => void;
    onUpdateStatus: (statusId: number, status: UpdateStatusSchema) => void;
    onDeleteStatus: (status: StatusSchema) => void;
    isEditorDrawerOpened: boolean;
    setIsEditorDrawerOpened: React.Dispatch<React.SetStateAction<boolean>>;
};

const StatusesContext = createContext<StatusesContextState | undefined>(
    undefined
);

const useStatusesContextState = () => {
    const { selectedBoard } = useBoardsContext();
    const {
        statuses,
        setStatuses,
        refetch: refetchStatuses,
    } = useStatusesList({
        boardId: selectedBoard?.id,
    });
    const [isEditorDrawerOpened, setIsEditorDrawerOpened] =
        useState<boolean>(false);

    useEffect(() => {
        refetchStatuses();
    }, [selectedBoard]);

    const updateStatus = useMutation({
        ...updateStatusMutation(),
        onError: error => {
            console.error(error);
            notifications.error({
                message: error.response?.data?.detail as string | undefined,
            });
            refetchStatuses();
        },
    });

    const { onCreateStatus, onUpdateStatus, onDeleteStatus } =
        useStatusesOperations({
            statuses,
            setStatuses,
            refetchStatuses,
            boardId: selectedBoard?.id,
        });

    return {
        statuses,
        setStatuses,
        updateStatus,
        refetchStatuses,
        onCreateStatus,
        onUpdateStatus,
        onDeleteStatus,
        isEditorDrawerOpened,
        setIsEditorDrawerOpened,
    };
};

type StatusesContextProviderProps = {
    children: React.ReactNode;
};

export const StatusesContextProvider: FC<StatusesContextProviderProps> = ({
    children,
}) => {
    const state = useStatusesContextState();

    return (
        <StatusesContext.Provider value={state}>
            {children}
        </StatusesContext.Provider>
    );
};

export const useStatusesContext = () => {
    const context = useContext(StatusesContext);
    if (!context) {
        throw new Error(
            "useStatusesContext must be used within a StatusesContextProvider"
        );
    }
    return context;
};
