import { useEffect, useMemo, useRef } from "react";
import { modals } from "@mantine/modals";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";

const useCreateFirstProject = () => {
    const hasOpened = useRef(false);
    const { projects, projectsCrud, isLoading } = useProjectsContext();
    const shouldOpen = useMemo(
        () => !isLoading && projects.length === 0,
        [isLoading, projects]
    );

    useEffect(() => {
        if (!shouldOpen || hasOpened.current) return;

        hasOpened.current = true;

        modals.openContextModal({
            modal: "createFirstProjectModal",
            withCloseButton: false,
            closeOnClickOutside: false,
            closeOnEscape: false,
            overlayProps: {
                color: "black",
                blur: 6,
                backgroundOpacity: 0.45,
            },
            innerProps: {
                onSubmit: values =>
                    projectsCrud.onCreate(values, modals.closeAll),
            },
        });
    }, [shouldOpen]);
};

export default useCreateFirstProject;
