"use client";

import React, { createContext, FC, useContext } from "react";
import { BoardsCrud, useBoardsCrud } from "@/hooks/cruds/useBoardsCrud";
import useBoardsList from "@/hooks/lists/useBoardsList";
import { BoardSchema, ProjectSchema } from "@/lib/client";

type ProjectBoardsContextState = {
    boards: BoardSchema[];
    setBoards: React.Dispatch<React.SetStateAction<BoardSchema[]>>;
    project: ProjectSchema;
    refetchBoards: () => void;
    boardsCrud: BoardsCrud;
};

const ProjectBoardsContext = createContext<
    ProjectBoardsContextState | undefined
>(undefined);

type Props = {
    project: ProjectSchema;
};

const useProjectBoardsContextState = ({ project }: Props) => {
    const {
        boards,
        setBoards,
        refetch: refetchBoards,
    } = useBoardsList({ projectId: project?.id });

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

    return {
        boards,
        setBoards,
        project,
        refetchBoards,
        boardsCrud,
    };
};

type ProjectBoardsContextProviderProps = {
    children: React.ReactNode;
} & Props;

export const ProjectBoardsContextProvider: FC<
    ProjectBoardsContextProviderProps
> = ({ children, ...props }) => {
    const state = useProjectBoardsContextState(props);

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

export const useProjectBoardsContext = () => {
    const context = useContext(ProjectBoardsContext);
    if (!context) {
        throw new Error(
            "useProjectBoardsContext must be used within a ProjectBoardsContextProvider"
        );
    }
    return context;
};
