"use client";

import React, { createContext, FC, useContext, useEffect } from "react";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { DealSchema, StatusSchema } from "@/client";
import useDealsList from "@/hooks/useDealsList";
import useStatusesList from "@/hooks/useStatusesList";

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

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

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

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

    return {
        statuses,
        setStatuses,
        deals,
        setDeals,
        refetchStatuses: refetch,
    };
};

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