"use client";

import React, {
    createContext,
    FC,
    useContext,
    useEffect,
    useState,
} from "react";
import useProjectsList from "@/hooks/useProjectsList";
import { useProjectsOperations } from "@/hooks/useProjectsOperations";
import { ProjectSchema, UpdateProjectSchema } from "@/lib/client";

type ProjectsContextState = {
    selectedProject: ProjectSchema | null;
    setSelectedProject: React.Dispatch<
        React.SetStateAction<ProjectSchema | null>
    >;
    projects: ProjectSchema[];
    onCreateProject: (name: string) => void;
    onUpdateProject: (projectId: number, project: UpdateProjectSchema) => void;
    onDeleteProject: (project: ProjectSchema) => void;
    isEditorDrawerOpened: boolean;
    setIsEditorDrawerOpened: React.Dispatch<React.SetStateAction<boolean>>;
};

const ProjectsContext = createContext<ProjectsContextState | undefined>(
    undefined
);

const useProjectsContextState = () => {
    const [isEditorDrawerOpened, setIsEditorDrawerOpened] =
        useState<boolean>(false);
    const {
        projects,
        setProjects,
        refetch: refetchProjects,
    } = useProjectsList();
    const [selectedProject, setSelectedProject] =
        useState<ProjectSchema | null>(null);

    useEffect(() => {
        if (projects.length > 0) {
            if (selectedProject) {
                setSelectedProject(
                    projects.find(
                        project => project.id === selectedProject.id
                    ) ?? null
                );
                return;
            }
            setSelectedProject(projects[0]);
            return;
        }
        setSelectedProject(null);
    }, [projects]);

    const { onCreateProject, onUpdateProject, onDeleteProject } =
        useProjectsOperations({
            projects,
            setProjects,
            refetchProjects,
        });

    return {
        projects,
        selectedProject,
        setSelectedProject,
        onCreateProject,
        onUpdateProject,
        onDeleteProject,
        isEditorDrawerOpened,
        setIsEditorDrawerOpened,
    };
};

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

export const ProjectsContextProvider: FC<ProjectsContextProviderProps> = ({
    children,
}) => {
    const state = useProjectsContextState();

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

export const useProjectsContext = () => {
    const context = useContext(ProjectsContext);
    if (!context) {
        throw new Error(
            "useProjectsContext must be used within a ProjectsContextProvider"
        );
    }
    return context;
};
