import { useCallback, useContext, useEffect } from "react";
import { ModalContext, hideModalCallbacks, modalActions, modalCallbacks, ModalIdContext } from "./modalContext";
import { getModalId } from "./utils";
import { register } from "./modalHelper";
export function useModal(modal, args) {
    const modals = useContext(ModalContext);
    const modalIdFromContext = useContext(ModalIdContext);
    let modalId;
    let isComponent = modal && typeof modal !== "string";
    if (!modal) {
        modalId = modalIdFromContext;
    } else {
        modalId = getModalId(modal);
    }
    if (!modalId) {
        throw new Error("modalId is required");
    }
    const id = modalId;
    useEffect(()=>{
        if (isComponent) {
            register(id, modal, args);
        }
    }, [
        isComponent,
        modalId,
        modal,
        args
    ]);
    const modalInfo = modals[id];
    const show = useCallback((args)=>modalActions.show(id, args), [
        id
    ]);
    const hide = useCallback(()=>modalActions.hide(id), [
        id
    ]);
    const remove = useCallback(()=>modalActions.remove(id), [
        id
    ]);
    const onOpenChange = useCallback((isOpen)=>{
        isOpen ? ()=>{} : hide();
    }, [
        id
    ]);
    const setStates = useCallback((states)=>modalActions.setStates(id, states), [
        id
    ]);
    const resolve = useCallback((args)=>{
        modalCallbacks[id]?.resolve(args);
        delete modalCallbacks[id];
    }, [
        id
    ]);
    const reject = useCallback((args)=>{
        modalCallbacks[id]?.reject(args);
        delete modalCallbacks[id];
    }, [
        id
    ]);
    const resolveHide = useCallback((args)=>{
        hideModalCallbacks[id]?.resolve(args);
        delete hideModalCallbacks[id];
    }, []);
    return {
        id,
        args: modalInfo?.args,
        visible: !!modalInfo?.visible,
        keepMounted: !!modalInfo?.keepMounted,
        show,
        hide,
        onOpenChange,
        setStates,
        remove,
        resolve,
        reject,
        resolveHide
    };
}

//# sourceMappingURL=useModal.js.map