import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import KeyboardArrowRight from "@mui/icons-material/KeyboardArrowRight";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { styled } from "@mui/material/styles";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import { ApIcon } from "../../../index.js";
import react from "react";
import { ApTypography } from "../../../ap-typography/index.js";
import { useScheduledCallback } from "../../hooks/use-scheduled-callback.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { AutopilotChatTooltip } from "../common/tooltip.js";
const StyledMenuItem = styled(MenuItem)(()=>({
        display: 'flex',
        alignItems: 'center',
        padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingS}`,
        gap: apollo_core.Spacing.SpacingMicro,
        cursor: 'pointer',
        fontSize: FontVariantToken.fontSizeS,
        color: 'var(--color-foreground)'
    }));
const NestedMenuContainer = styled('div')({
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingMicro,
    width: '100%',
    justifyContent: 'space-between'
});
const MenuItemContent = styled('div')({
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingMicro
});
const NestedMenuItem = /*#__PURE__*/ react.memo(/*#__PURE__*/ react.forwardRef(({ action, onActionClick, isFirst = false, portalContainer }, ref)=>{
    const [open, setOpen] = react.useState(false);
    const menuItemRef = react.useRef(null);
    const submenuRef = react.useRef(null);
    const closeTimeoutRef = react.useRef(null);
    const nestedPopoverActionRef = react.useRef(null);
    const updateNestedPosition = react.useCallback(()=>{
        if (nestedPopoverActionRef.current) nestedPopoverActionRef.current.updatePosition();
    }, []);
    const scheduleNestedPositionUpdate = useScheduledCallback(updateNestedPosition);
    const handleNestedTransitionEnter = react.useCallback(()=>{
        scheduleNestedPositionUpdate();
    }, [
        scheduleNestedPositionUpdate
    ]);
    const handleNestedTransitionEntered = react.useCallback(()=>{
        scheduleNestedPositionUpdate();
    }, [
        scheduleNestedPositionUpdate
    ]);
    react.useImperativeHandle(ref, ()=>menuItemRef.current);
    react.useEffect(()=>()=>{
            if (closeTimeoutRef.current) clearTimeout(closeTimeoutRef.current);
        }, []);
    const handleMouseEnter = react.useCallback(()=>{
        if (closeTimeoutRef.current) {
            clearTimeout(closeTimeoutRef.current);
            closeTimeoutRef.current = null;
        }
        if (!action.disabled && action.children && action.children.length > 0) setOpen(true);
    }, [
        action.disabled,
        action.children
    ]);
    const handleMouseLeave = react.useCallback(()=>{
        closeTimeoutRef.current = setTimeout(()=>{
            setOpen(false);
        }, 150);
    }, []);
    const handleSubmenuMouseEnter = react.useCallback(()=>{
        if (closeTimeoutRef.current) {
            clearTimeout(closeTimeoutRef.current);
            closeTimeoutRef.current = null;
        }
    }, []);
    const handleSubmenuMouseLeave = react.useCallback(()=>{
        setOpen(false);
    }, []);
    const handleClick = react.useCallback((event)=>{
        event.stopPropagation();
        if (!action.disabled && !action.children) onActionClick(action);
    }, [
        onActionClick,
        action
    ]);
    const handleKeyDown = react.useCallback((event)=>{
        if (action.disabled) return;
        if (action.children && action.children.length > 0) {
            if ('ArrowRight' === event.key) {
                event.preventDefault();
                event.stopPropagation();
                setOpen(true);
                requestAnimationFrame(()=>{
                    const firstChild = submenuRef.current?.querySelector('[role="menuitem"]');
                    firstChild?.focus();
                });
            } else if ('Enter' === event.key || ' ' === event.key) {
                event.preventDefault();
                event.stopPropagation();
                setOpen(!open);
            }
        } else if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            event.stopPropagation();
            onActionClick(action);
        }
    }, [
        action,
        open,
        onActionClick
    ]);
    const handleClose = react.useCallback(()=>{
        setOpen(false);
        menuItemRef.current?.focus();
    }, []);
    const handleChildClick = react.useCallback((childAction)=>{
        onActionClick(childAction);
        setOpen(false);
    }, [
        onActionClick
    ]);
    const handleSubmenuKeyDown = react.useCallback((event)=>{
        if ('ArrowLeft' === event.key) {
            event.preventDefault();
            event.stopPropagation();
            handleClose();
        } else if ('ArrowUp' === event.key || 'ArrowDown' === event.key) {
            event.preventDefault();
            event.stopPropagation();
            const menuItems = submenuRef.current?.querySelectorAll('[role="menuitem"]:not([disabled])');
            if (!menuItems || 0 === menuItems.length) return;
            const currentIndex = Array.from(menuItems).findIndex((item)=>item === document.activeElement);
            let nextIndex;
            nextIndex = 'ArrowDown' === event.key ? -1 === currentIndex ? 0 : (currentIndex + 1) % menuItems.length : -1 === currentIndex ? menuItems.length - 1 : (currentIndex - 1 + menuItems.length) % menuItems.length;
            menuItems[nextIndex]?.focus();
        } else if ('ArrowRight' === event.key) {
            event.preventDefault();
            event.stopPropagation();
        }
    }, [
        handleClose
    ]);
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx(StyledMenuItem, {
                ref: menuItemRef,
                onClick: handleClick,
                onKeyDown: handleKeyDown,
                onMouseEnter: handleMouseEnter,
                onMouseLeave: handleMouseLeave,
                disabled: action.disabled,
                tabIndex: isFirst ? 0 : -1,
                children: /*#__PURE__*/ jsx(AutopilotChatTooltip, {
                    placement: "left",
                    disableInteractive: true,
                    title: action.description ? /*#__PURE__*/ jsx(ApTypography, {
                        color: 'var(--color-foreground-inverse)',
                        variant: FontVariantToken.fontSizeS,
                        children: action.description
                    }) : null,
                    children: /*#__PURE__*/ jsxs(NestedMenuContainer, {
                        children: [
                            /*#__PURE__*/ jsxs(MenuItemContent, {
                                children: [
                                    action.icon && /*#__PURE__*/ jsx(ApIcon, {
                                        variant: "outlined",
                                        name: action.icon,
                                        size: apollo_core.Icon.IconXs
                                    }),
                                    /*#__PURE__*/ jsx(ApTypography, {
                                        variant: FontVariantToken.fontSizeS,
                                        children: action.name
                                    })
                                ]
                            }),
                            action.children && action.children.length > 0 && /*#__PURE__*/ jsx(KeyboardArrowRight, {
                                fontSize: "inherit"
                            })
                        ]
                    })
                })
            }),
            action.children && action.children.length > 0 && /*#__PURE__*/ jsx(Menu, {
                hideBackdrop: true,
                style: {
                    pointerEvents: 'none'
                },
                open: open,
                anchorEl: menuItemRef.current,
                onClose: handleClose,
                container: portalContainer,
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'left'
                },
                transformOrigin: {
                    vertical: 'top',
                    horizontal: 'right'
                },
                autoFocus: false,
                disableAutoFocus: true,
                disableEnforceFocus: true,
                action: nestedPopoverActionRef,
                MenuListProps: {
                    sx: {
                        padding: 0
                    },
                    disableListWrap: true
                },
                slotProps: {
                    paper: {
                        sx: {
                            marginRight: apollo_core.Spacing.SpacingXs
                        }
                    }
                },
                TransitionProps: {
                    onEnter: handleNestedTransitionEnter,
                    onEntered: handleNestedTransitionEntered
                },
                children: /*#__PURE__*/ jsx("div", {
                    ref: submenuRef,
                    style: {
                        pointerEvents: 'auto'
                    },
                    onKeyDown: handleSubmenuKeyDown,
                    onMouseEnter: handleSubmenuMouseEnter,
                    onMouseLeave: handleSubmenuMouseLeave,
                    children: action.children.map((child)=>/*#__PURE__*/ jsx(StyledMenuItem, {
                            onClick: ()=>handleChildClick(child),
                            onKeyDown: (e)=>{
                                if ('Enter' === e.key || ' ' === e.key) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    handleChildClick(child);
                                }
                            },
                            disabled: child.disabled,
                            tabIndex: 0,
                            children: /*#__PURE__*/ jsx(AutopilotChatTooltip, {
                                placement: "left",
                                disableInteractive: true,
                                title: child.description ? /*#__PURE__*/ jsx(ApTypography, {
                                    color: 'var(--color-foreground-inverse)',
                                    variant: FontVariantToken.fontSizeS,
                                    children: child.description
                                }) : null,
                                children: /*#__PURE__*/ jsxs(MenuItemContent, {
                                    children: [
                                        child.icon && /*#__PURE__*/ jsx(ApIcon, {
                                            variant: "outlined",
                                            name: child.icon,
                                            size: apollo_core.Icon.IconXs
                                        }),
                                        /*#__PURE__*/ jsx(ApTypography, {
                                            variant: FontVariantToken.fontSizeS,
                                            children: child.name
                                        })
                                    ]
                                })
                            })
                        }, child.id))
                })
            })
        ]
    });
}));
const AutopilotChatHeaderActionMenu = /*#__PURE__*/ react.memo(({ actions, onActionClick, anchorEl, open, onClose })=>{
    const { portalContainer } = useChatState();
    const firstItemRef = react.useRef(null);
    const popoverActionRef = react.useRef(null);
    const updatePosition = react.useCallback(()=>{
        if (popoverActionRef.current) popoverActionRef.current.updatePosition();
    }, []);
    const schedulePositionUpdate = useScheduledCallback(updatePosition);
    const handleTransitionEnter = react.useCallback(()=>{
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    const handleTransitionEntered = react.useCallback(()=>{
        if (firstItemRef.current) firstItemRef.current.focus();
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    return /*#__PURE__*/ jsx(Menu, {
        open: open,
        anchorEl: anchorEl,
        onClose: onClose,
        container: portalContainer,
        anchorOrigin: {
            vertical: 'bottom',
            horizontal: 'right'
        },
        transformOrigin: {
            vertical: 'top',
            horizontal: 'right'
        },
        variant: "menu",
        MenuListProps: {
            autoFocusItem: false
        },
        action: popoverActionRef,
        TransitionProps: {
            onEnter: handleTransitionEnter,
            onEntered: handleTransitionEntered
        },
        children: actions.map((action, index)=>/*#__PURE__*/ jsx(NestedMenuItem, {
                action: action,
                onActionClick: onActionClick,
                ref: 0 === index ? firstItemRef : void 0,
                isFirst: 0 === index,
                portalContainer: portalContainer
            }, action.id))
    });
});
export { AutopilotChatHeaderActionMenu };
