"use client";

import React, { useState } from "react";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { BoardsCrud, useBoardsCrud } from "@/hooks/cruds/useBoardsCrud";
import useBoardsList from "@/hooks/lists/useBoardsList";
import { BoardSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

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

const useBoardsContextState = (): BoardsContextState => {
    const { selectedProject: project } = useProjectsContext();
    const {
        boards,
        setBoards,
        refetch: refetchBoards,
        queryKey,
    } = useBoardsList({ projectId: project?.id });

    const [selectedBoardId, setSelectedBoardId] = useState<number | null>(null);
    const selectedBoard =
        boards.find(board => board.id === selectedBoardId) ?? null;

    if (selectedBoard === null && boards.length > 0) {
        setSelectedBoardId(boards[0].id);
    }

    const boardsCrud = useBoardsCrud({
        boards,
        queryKey,
        projectId: project?.id,
    });

    return {
        boards,
        setBoards,
        selectedBoard,
        setSelectedBoardId,
        refetchBoards,
        boardsCrud,
    };
};

export const [BoardsContextProvider, useBoardsContext] =
    makeContext<BoardsContextState>(useBoardsContextState, "Boards");
