"use client";

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

type BoardsContextState = {
    boards: BoardSchema[];
    setBoards: React.Dispatch<React.SetStateAction<BoardSchema[]>>;
    selectedBoard: BoardSchema | null;
    setSelectedBoard: React.Dispatch<React.SetStateAction<BoardSchema | null>>;
    refetchBoards: () => void;
    onCreateBoard: (name: string) => void;
    onUpdateBoard: (boardId: number, board: UpdateBoardSchema) => void;
    onDeleteBoard: (boardId: number) => 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]);

    const { onCreateBoard, onUpdateBoard, onDeleteBoard } = useBoardsOperations(
        {
            boards,
            setBoards,
            refetchBoards,
            projectId: project?.id,
        }
    );

    return {
        boards,
        setBoards,
        selectedBoard,
        setSelectedBoard,
        refetchBoards,
        onCreateBoard,
        onUpdateBoard,
        onDeleteBoard,
    };
};

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