"use client";

import React, {
    createContext,
    FC,
    useContext,
    useEffect,
    useState,
} from "react";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { BoardSchema } from "@/client";
import useBoardsList from "@/hooks/useBoardsList";

type BoardsContextState = {
    boards: BoardSchema[];
    setBoards: React.Dispatch<React.SetStateAction<BoardSchema[]>>;
    selectedBoard: BoardSchema | null;
    setSelectedBoard: React.Dispatch<React.SetStateAction<BoardSchema | null>>;
    refetchBoards: () => void;
};

const BoardsContext = createContext<BoardsContextState | undefined>(undefined);

const useBoardsContextState = () => {
    const { selectedProject: project } = useProjectsContext();
    const { boards, setBoards, refetch: refetchBoards } = useBoardsList({ projectId: project?.id });
    const [selectedBoard, setSelectedBoard] = useState<BoardSchema | null>(
        null
    );

    useEffect(() => {
        if (boards.length > 0 && selectedBoard === null) {
            setSelectedBoard(boards[0]);
            return;
        }

        if (selectedBoard) {
            let newBoard = boards.find(board => board.id === selectedBoard.id);

            if (!newBoard && boards.length > 0) {
                newBoard = boards[0];
            }
            setSelectedBoard(newBoard ?? null);
        }
    }, [boards]);

    return {
        boards,
        setBoards,
        selectedBoard,
        setSelectedBoard,
        refetchBoards,
    };
};

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

export const BoardsContextProvider: FC<BoardsContextProviderProps> = ({
    children,
}) => {
    const state = useBoardsContextState();

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

export const useBoardsContext = () => {
    const context = useContext(BoardsContext);
    if (!context) {
        throw new Error(
            "useBoardsContext must be used within a BoardsContextProvider"
        );
    }
    return context;
};
