"use client";

import { useMemo, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { ProjectsCrud, useProjectsCrud } from "@/hooks/cruds/useProjectsCrud";
import useProjectsList from "@/hooks/lists/useProjectsList";
import useIsMobile from "@/hooks/utils/useIsMobile";
import { ProjectSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";
import { ModuleNames } from "@/modules/modules";

type ProjectsContextState = {
    projects: ProjectSchema[];
    isLoading: boolean;
    selectedProject: ProjectSchema | null;
    setSelectedProjectId: (id: number | null) => void;
    refetchProjects: () => void;
    projectsCrud: ProjectsCrud;
    modulesSet: Set<ModuleNames>;
};

const useProjectsContextState = (): ProjectsContextState => {
    const {
        projects,
        refetch: refetchProjects,
        queryKey,
        isLoading,
    } = useProjectsList();
    const isMobile = useIsMobile();
    const pathname = usePathname();
    const router = useRouter();

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

    const modulesSet = useMemo(
        () => new Set(selectedProject?.modules.map(m => m.key as ModuleNames)),
        [selectedProject]
    );

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

    const projectsCrud = useProjectsCrud({ queryKey });

    const handleSetSelectedProjectId = (id: number | null) => {
        if (!isMobile && pathname !== "/deals") router.push("/deals");
        setSelectedProjectId(id);
    };

    return {
        projects,
        isLoading,
        selectedProject,
        refetchProjects,
        setSelectedProjectId: handleSetSelectedProjectId,
        projectsCrud,
        modulesSet,
    };
};

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