"use client";

import React, { createContext, FC, useContext } from "react";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { StatusesCrud, useStatusesCrud } from "@/hooks/useStatusesCrud";
import useStatusesList from "@/hooks/useStatusesList";
import { StatusSchema } from "@/lib/client";

type StatusesContextState = {
    statuses: StatusSchema[];
    setStatuses: React.Dispatch<React.SetStateAction<StatusSchema[]>>;
    refetchStatuses: () => void;
    statusesCrud: StatusesCrud;
};

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

const useStatusesContextState = () => {
    const { selectedBoard } = useBoardsContext();
    const {
        statuses,
        setStatuses,
        refetch: refetchStatuses,
    } = useStatusesList({
        boardId: selectedBoard?.id,
    });

    const statusesCrud = useStatusesCrud({
        statuses,
        setStatuses,
        refetchStatuses,
        boardId: selectedBoard?.id,
    });

    return {
        statuses,
        setStatuses,
        refetchStatuses,
        statusesCrud,
    };
};

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;
};
