import React, { createContext, FC, useContext, useEffect, useState } from "react";
import { ProjectSchema } from "../client";
import useProjects from "../hooks/useProjects.tsx";

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

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

const useProjectsContextState = () => {
    const { projects, refetchProjects } = useProjects();
    const [selectedProject, setSelectedProject] = useState<ProjectSchema | null>(null);

    const refetch = () => {
        refetchProjects();
    };

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

    return {
        projects,
        refetchProjects: refetch,
        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;
};
