import { useCallback, useEffect, useRef, useState } from 'react';
import { useEventCallbackRef } from '../../utils/hooks/useEventCallbackRef';
export default function useSinglePopoverVisible(defaultSelected, setSelected, onOpen, onClose, disabled, openPanel) {
    var _a = useState(openPanel !== null && openPanel !== void 0 ? openPanel : false), panelVisible = _a[0], setPanelVisible = _a[1];
    var onOpenRef = useEventCallbackRef(onOpen);
    var onCloseRef = useEventCallbackRef(onClose);
    var defaultSelectedRef = useRef(defaultSelected);
    defaultSelectedRef.current = defaultSelected;
    useEffect(function () {
        setPanelVisible(openPanel !== null && openPanel !== void 0 ? openPanel : false);
    }, [openPanel]);
    var onVisibleChange = useCallback(function () {
        if (openPanel !== undefined || disabled)
            return;
        setPanelVisible(!panelVisible);
    }, [panelVisible, openPanel, disabled]);
    var mounted = useRef();
    useEffect(function () {
        var _a, _b;
        if (!mounted.current) {
            mounted.current = true;
        }
        else {
            if (panelVisible) {
                (_a = onOpenRef === null || onOpenRef === void 0 ? void 0 : onOpenRef.current) === null || _a === void 0 ? void 0 : _a.call(onOpenRef);
            }
            else {
                setSelected(defaultSelectedRef.current);
                (_b = onCloseRef === null || onCloseRef === void 0 ? void 0 : onCloseRef.current) === null || _b === void 0 ? void 0 : _b.call(onCloseRef);
            }
        }
    }, [panelVisible, defaultSelectedRef, onOpenRef, onCloseRef, setSelected]);
    return { panelVisible: panelVisible, setPanelVisible: setPanelVisible, onVisibleChange: onVisibleChange };
}
