"use client";

import React, { useState } from "react";
import { ProjectsCrud, useProjectsCrud } from "@/hooks/cruds/useProjectsCrud";
import useProjectsList from "@/hooks/lists/useProjectsList";
import { ProjectSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

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

const useProjectsContextState = (): ProjectsContextState => {
    const { projects, refetch: refetchProjects, queryKey } = useProjectsList();

    const [selectedProjectId, setSelectedProjectId] = useState<number | null>(
        null
    );
    const selectedProject =
        projects.find(project => project.id === selectedProjectId) ?? null;

    if (selectedProject === null && projects.length > 0) {
        setSelectedProjectId(projects[0].id);
    }

    const projectsCrud = useProjectsCrud({ queryKey });

    return {
        projects,
        selectedProject,
        refetchProjects,
        setSelectedProjectId,
        projectsCrud,
    };
};

export const [ProjectsContextProvider, useProjectsContext] =
    makeContext<ProjectsContextState>(useProjectsContextState, "Projects");
