"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: (board: BoardSchema) => void;
    isEditorDrawerOpened: boolean;
    setIsEditorDrawerOpened: React.Dispatch<React.SetStateAction<boolean>>;
};

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
    );
    const [isEditorDrawerOpened, setIsEditorDrawerOpened] =
        useState<boolean>(false);

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

        if (!selectedBoard) return;

        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,
        isEditorDrawerOpened,
        setIsEditorDrawerOpened,
    };
};

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