"use client";

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

type ProjectsContextState = {
    selectedProject: ProjectSchema | null;
    setSelectedProject: React.Dispatch<
        React.SetStateAction<ProjectSchema | null>
    >;
    projects: ProjectSchema[];
};

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

const useProjectsContextState = () => {
    const { projects } = 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]);

    return {
        projects,
        selectedProject,
        setSelectedProject,
    };
};

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