import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import KeyboardArrowDown from "@mui/icons-material/KeyboardArrowDown";
import { Menu, MenuItem, styled } from "@mui/material";
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 { AutopilotChatInternalEvent } from "../../service/index.js";
import { AutopilotChatActionButton } from "./action-button.js";
import { AutopilotChatTooltip } from "./tooltip.js";
const DropdownPickerContainer = styled('div')({
    position: 'relative',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingMicro
});
const SelectedOptionContainer = styled('div')(()=>({
        display: 'flex',
        alignItems: 'center',
        color: 'var(--color-foreground-light)',
        gap: apollo_core.Spacing.SpacingMicro,
        cursor: 'pointer',
        borderRadius: apollo_core.Border.BorderRadiusM,
        padding: apollo_core.Spacing.SpacingMicro,
        '&:focus': {
            outline: '2px solid var(--color-focus-indicator)',
            outlineOffset: '2px'
        },
        '& .arrow-icon': {
            transition: 'transform 0.2s ease-in-out',
            transform: 'rotate(0deg)'
        },
        '& .arrow-icon.open': {
            transform: 'rotate(180deg)'
        }
    }));
const StyledMenuItem = styled(MenuItem)({
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingMicro
});
function DropdownPicker({ options, selectedOption, onSelect, useIcon, ariaLabel, chatServiceInstance, iconVariant = 'outlined' }) {
    const { _ } = useLingui();
    const { spacing, theming, portalContainer } = useChatState();
    const [anchorEl, setAnchorEl] = react.useState(null);
    const popoverActionRef = react.useRef(null);
    const open = Boolean(anchorEl);
    const updatePosition = react.useCallback(()=>{
        if (popoverActionRef.current) popoverActionRef.current.updatePosition();
    }, []);
    const schedulePositionUpdate = useScheduledCallback(updatePosition);
    const handleTransitionEnter = react.useCallback(()=>{
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    const handleTransitionEntered = react.useCallback(()=>{
        schedulePositionUpdate();
    }, [
        schedulePositionUpdate
    ]);
    const handleClose = react.useCallback(()=>{
        setAnchorEl(null);
        if (chatServiceInstance) requestAnimationFrame(()=>{
            chatServiceInstance.__internalService__.publish(AutopilotChatInternalEvent.SetInputFocused, true);
        });
    }, [
        chatServiceInstance
    ]);
    const handleOptionChange = react.useCallback((option)=>{
        onSelect(option);
        handleClose();
    }, [
        onSelect,
        handleClose
    ]);
    const handleClick = react.useCallback((event)=>{
        event.stopPropagation();
        const target = event.currentTarget instanceof HTMLButtonElement ? event.currentTarget.parentElement : event.currentTarget;
        setAnchorEl(target);
    }, []);
    const handleKeyDown = react.useCallback((event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            handleClick(event);
        }
    }, [
        handleClick
    ]);
    const renderSelectedOption = react.useCallback(()=>{
        if (useIcon) return /*#__PURE__*/ jsx(AutopilotChatActionButton, {
            iconName: selectedOption.icon ?? '',
            variant: iconVariant,
            onClick: handleClick,
            tooltipPlacement: "top-start",
            tooltip: open ? null : /*#__PURE__*/ jsxs(Fragment, {
                children: [
                    /*#__PURE__*/ jsx(ApTypography, {
                        color: 'var(--color-foreground-inverse)',
                        variant: FontVariantToken.fontSizeM,
                        children: selectedOption.name
                    }),
                    selectedOption.description && /*#__PURE__*/ jsx(ApTypography, {
                        color: 'var(--color-foreground-inverse)',
                        variant: FontVariantToken.fontSizeXs,
                        children: selectedOption.description
                    })
                ]
            }),
            ariaLabel: _({
                id: 'autopilot-chat.common.model-selector'
            })
        });
        return /*#__PURE__*/ jsx(AutopilotChatTooltip, {
            placement: "top-start",
            title: !open && selectedOption.description ? /*#__PURE__*/ jsx(ApTypography, {
                color: 'var(--color-foreground-inverse)',
                variant: FontVariantToken.fontSizeS,
                children: selectedOption.description
            }) : null,
            children: /*#__PURE__*/ jsxs(SelectedOptionContainer, {
                onClick: handleClick,
                onKeyDown: handleKeyDown,
                tabIndex: 0,
                role: "button",
                "aria-haspopup": "true",
                "aria-expanded": open,
                "aria-label": _({
                    id: 'autopilot-chat.common.mode-selector'
                }),
                children: [
                    selectedOption.icon && /*#__PURE__*/ jsx(ApIcon, {
                        variant: "outlined",
                        name: selectedOption.icon,
                        size: apollo_core.Icon.IconXs
                    }),
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: spacing.primaryFontToken,
                        children: selectedOption.name
                    }),
                    /*#__PURE__*/ jsx(KeyboardArrowDown, {
                        className: `arrow-icon ${open ? 'open' : ''}`,
                        fontSize: "inherit"
                    })
                ]
            })
        });
    }, [
        selectedOption,
        useIcon,
        open,
        handleClick,
        handleKeyDown,
        iconVariant,
        spacing,
        _
    ]);
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx(DropdownPickerContainer, {
                children: renderSelectedOption()
            }),
            /*#__PURE__*/ jsx(Menu, {
                open: open,
                anchorEl: anchorEl,
                onClose: handleClose,
                container: portalContainer,
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'left'
                },
                transformOrigin: {
                    vertical: 'bottom',
                    horizontal: 'left'
                },
                MenuListProps: {
                    'aria-label': ariaLabel,
                    dense: true
                },
                action: popoverActionRef,
                TransitionProps: {
                    onEnter: handleTransitionEnter,
                    onEntered: handleTransitionEntered
                },
                children: options.map((option)=>/*#__PURE__*/ jsx(StyledMenuItem, {
                        onClick: ()=>handleOptionChange(option),
                        selected: selectedOption.id === option.id,
                        children: /*#__PURE__*/ jsx(AutopilotChatTooltip, {
                            placement: theming?.chatMenu?.groupItemTooltipPlacement ?? 'left',
                            title: option.description ? /*#__PURE__*/ jsx(ApTypography, {
                                color: 'var(--color-foreground-inverse)',
                                variant: FontVariantToken.fontSizeS,
                                children: option.description
                            }) : null,
                            children: /*#__PURE__*/ jsxs("div", {
                                style: {
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: apollo_core.Spacing.SpacingMicro,
                                    width: '100%'
                                },
                                children: [
                                    option.icon && /*#__PURE__*/ jsx(ApIcon, {
                                        variant: "outlined",
                                        name: option.icon,
                                        size: apollo_core.Icon.IconXs
                                    }),
                                    /*#__PURE__*/ jsx(ApTypography, {
                                        variant: spacing.primaryFontToken,
                                        children: option.name
                                    })
                                ]
                            })
                        })
                    }, String(option.id)))
            })
        ]
    });
}
export { DropdownPicker };
