"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 = {
    selectedProject: ProjectSchema | null;
    setSelectedProjectId: (id: number | null) => void;
    refetchProjects: () => void;
    projects: ProjectSchema[];
    projectsCrud: ProjectsCrud;
    modulesSet: Set<ModuleNames>;
};

const useProjectsContextState = (): ProjectsContextState => {
    const { projects, refetch: refetchProjects, queryKey } = 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,
        selectedProject,
        refetchProjects,
        setSelectedProjectId: handleSetSelectedProjectId,
        projectsCrud,
        modulesSet,
    };
};

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