import { useEffect, useCallback, useReducer, Children } from 'react';
import { SIDEBAR_SUBMENU_ANIMATION_TYPES, ExpandCollapseTriggers, } from '../constants';
export const useMenuState = ({ itemKey, selectedKey, children, disabled, onExpand, onCollapse, onToggle, onClick, }) => {
    const [state, setState] = useReducer((currentState, newState) => ({ ...currentState, ...newState }), {
        lastTrigger: null,
        isMenuOpen: false,
        isItemKeySelected: false,
        animation: SIDEBAR_SUBMENU_ANIMATION_TYPES.CLOSED,
    });
    useEffect(() => {
        const selectedKeyMatchesChildKey = Children.toArray(children).some(({ props }) => props && props.itemKey === selectedKey);
        const selectedKeyMatchesItemKey = itemKey === selectedKey;
        const isItemKeySelected = selectedKeyMatchesItemKey || selectedKeyMatchesChildKey;
        setState({ isItemKeySelected });
    }, [selectedKey, itemKey, children, disabled]);
    useEffect(() => {
        const isMenuOpen = state.isItemKeySelected && !disabled;
        setState({ isMenuOpen, lastTrigger: ExpandCollapseTriggers.select });
    }, [state.isItemKeySelected, disabled]);
    useEffect(() => {
        if (state.lastTrigger) {
            const animation = state.isMenuOpen
                ? SIDEBAR_SUBMENU_ANIMATION_TYPES.OPENING
                : SIDEBAR_SUBMENU_ANIMATION_TYPES.CLOSING;
            setState({ animation });
            state.isMenuOpen
                ? onExpand && onExpand(state.lastTrigger)
                : onCollapse && onCollapse(state.lastTrigger);
        }
        setState({ lastTrigger: null });
    }, [state.isMenuOpen, state.lastTrigger, disabled, onExpand, onCollapse]);
    const _onClick = useCallback(e => {
        if (state.isItemKeySelected) {
            setState({
                lastTrigger: ExpandCollapseTriggers.click,
                isMenuOpen: !state.isMenuOpen,
            });
            onToggle && onToggle();
            e.preventDefault();
        }
        onClick(e);
    }, [state.isItemKeySelected, state.isMenuOpen, onToggle, onClick]);
    return {
        isMenuOpen: state.isMenuOpen,
        isItemKeySelected: state.isItemKeySelected,
        animation: state.animation,
        _onClick,
    };
};
//# sourceMappingURL=useMenuState.js.map