import React, { createContext, FC, useContext } from "react";
import { useDisclosure } from "@mantine/hooks";

type ProjectsEditorContextState = {
    openedProjectsEditor: boolean;
    openProjectsEditor: () => void;
    closeProjectsEditor: () => void;
};

const ProjectsEditorContext = createContext<ProjectsEditorContextState | undefined>(
    undefined,
);

const useProjectsEditorContextState = () => {
    const [opened, { open, close }] = useDisclosure(false);

    return {
        openedProjectsEditor: opened,
        openProjectsEditor: open,
        closeProjectsEditor: close,
    };
};

type ProjectsEditorContextProviderProps = {
    children: React.ReactNode;
};

export const ProjectsEditorContextProvider: FC<ProjectsEditorContextProviderProps> = ({ children }) => {
    const state = useProjectsEditorContextState();

    return (
        <ProjectsEditorContext.Provider value={state}>
            {children}
        </ProjectsEditorContext.Provider>
    );
};

export const useProjectsEditorContext = () => {
    const context = useContext(ProjectsEditorContext);
    if (!context) {
        throw new Error(
            "useProjectEditorContext must be used within a ProjectEditorContextProvider",
        );
    }
    return context;
};
