/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-7eefd09
 * Released under the MIT license.
 */

import { jsx as _jsx } from "react/jsx-runtime";
import { useMemo, useRef, useState, } from 'react';
import { useEvent } from '../../../_internal/index.js';
import { mergeProps } from '../../../utils/react/index.js';
import { DialogContainer } from './DialogContainer.js';
/**
 * Generic hook to manage a dialog component.
 *
 * @param Component - A React component that represents the dialog content. It must accept props of type P.
 * @param defaultContainerProps - Default props to pass to the DialogContainer.
 * @returns An object with `open` function to open the dialog with provided props and `rendered` JSX element to include in your component tree.
 */
export function useDialogContainer(Component, defaultContainerProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [componentProps, setComponentProps] = useState(null);
    const [containerProps, setContainerProps] = useState(null);
    const setupRef = useRef(false);
    function setupCheck() {
        if (!setupRef.current) {
            throw new Error('useDialogContainer: DialogContainer must be rendered. Use `rendered` property to include it in your component tree.');
        }
    }
    // 'open' accepts props required by the Component and opens the dialog
    const open = useEvent((props, containerProps) => {
        setupCheck();
        setComponentProps(props);
        setContainerProps(containerProps ?? null);
        setIsOpen(true);
    });
    const update = useEvent((props, containerProps) => {
        setupCheck();
        setComponentProps(props);
        setContainerProps(containerProps ?? null);
    });
    const close = useEvent(() => {
        setIsOpen(false);
    });
    // Render the dialog only when componentProps is set
    const renderedDialog = useMemo(() => {
        if (!componentProps)
            return null;
        return (_jsx(DialogContainer, { isOpen: isOpen, onDismiss: close, ...mergeProps(defaultContainerProps, containerProps || undefined), children: _jsx(Component, { ...componentProps }) }));
    }, [componentProps, containerProps, isOpen, defaultContainerProps]);
    return {
        open,
        update,
        close,
        get rendered() {
            setupRef.current = true;
            return renderedDialog;
        },
    };
}

        