"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;
    refetchDeals: () => void;
};

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

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

    const {
        deals,
        setDeals,
        refetch: refetchDeals,
    } = useDealsList({ boardId: selectedBoard?.id });

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

    return {
        statuses,
        setStatuses,
        deals,
        setDeals,
        refetchStatuses,
        refetchDeals,
    };
};

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