import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import CircularProgress from "@mui/material/CircularProgress";
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 { ApButton, ApIcon, ApTypography } from "../../../../index.js";
import react, { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
import { List, useListRef } from "react-window";
import { ApSkeleton } from "../../../ap-skeleton/index.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { isResourceSelector, useAutopilotChatResourcePicker } from "../../providers/resource-picker-provider.js";
import { CHAT_RESOURCE_PICKER_ITEM_HEIGHT, CHAT_RESOURCE_PICKER_LOAD_MORE_THRESHOLD, CHAT_RESOURCE_PICKER_MAX_SKELETON_COUNT, CHAT_RESOURCE_PICKER_MENU_MAX_HEIGHT, CHAT_RESOURCE_PICKER_MENU_WIDTH, CHAT_RESOURCE_PICKER_MIN_SKELETON_COUNT, CHAT_RESOURCE_PICKER_TOOLTIP_ENTER_DELAY } from "../../service/index.js";
import { AutopilotChatIconButton } from "../common/icon-button.js";
import { AutopilotChatTooltip } from "../common/tooltip.js";
const ellipsisStyle = {
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap'
};
const StyledMenuItem = styled(MenuItem)({
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingXs,
    justifyContent: 'space-between'
});
const ResourceItemContent = styled('div')({
    display: 'flex',
    alignItems: 'center',
    gap: apollo_core.Spacing.SpacingXs,
    flex: 1,
    minWidth: 0
});
const ErrorContainer = styled('div')(()=>({
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: apollo_core.Spacing.SpacingS,
        padding: apollo_core.Padding.PadXxxl,
        color: 'var(--color-error-text)'
    }));
const EmptyContainer = styled('div')(()=>({
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: `${apollo_core.Padding.PadXxl} ${apollo_core.Padding.PadXxxl}`,
        color: 'var(--color-foreground-de-emp)'
    }));
const DrillDownHeader = styled('div')(()=>({
        display: 'flex',
        alignItems: 'center',
        gap: apollo_core.Spacing.SpacingMicro,
        padding: `${apollo_core.Padding.PadXs} ${apollo_core.Padding.PadXxxl} ${apollo_core.Padding.PadXs} ${apollo_core.Padding.PadXxl}`,
        backgroundColor: 'var(--color-background-secondary)'
    }));
const SkeletonItem = styled(StyledMenuItem)({
    pointerEvents: 'none'
});
const StyledResourceList = styled(List)({
    '&::-webkit-scrollbar': {
        width: '6px'
    },
    '&::-webkit-scrollbar-track': {
        background: 'transparent'
    },
    '&::-webkit-scrollbar-thumb': {
        background: 'var(--color-border-de-emp)',
        borderRadius: '3px'
    }
});
const loaderRowStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
};
const preventDefaultMouseDown = (e)=>e.preventDefault();
const MENU_SLOT_PROPS = {
    paper: {
        sx: {
            width: CHAT_RESOURCE_PICKER_MENU_WIDTH,
            maxHeight: CHAT_RESOURCE_PICKER_MENU_MAX_HEIGHT,
            overflowY: 'hidden',
            display: 'flex',
            flexDirection: 'column'
        }
    }
};
const VirtualizedResourceRow = ({ index, style, ariaAttributes, items, selectedIndex, navigationMode, handleItemClick, onMouseEnterItem, tooltipPlacement, fontToken })=>{
    if (index >= items.length) return /*#__PURE__*/ jsx("div", {
        style: {
            ...style,
            ...loaderRowStyle
        },
        children: /*#__PURE__*/ jsx(CircularProgress, {
            size: 20
        })
    });
    const item = items[index];
    const isSelected = index === selectedIndex;
    const isCategory = isResourceSelector(item);
    const tooltipContent = item.tooltip;
    const isKeyboardSelected = isSelected && 'keyboard' === navigationMode;
    const menuItem = /*#__PURE__*/ jsxs(StyledMenuItem, {
        id: `resource-item-${item.id}`,
        selected: isSelected,
        onClick: ()=>handleItemClick(item),
        onMouseEnter: ()=>onMouseEnterItem(index),
        style: style,
        ...ariaAttributes,
        children: [
            /*#__PURE__*/ jsxs(ResourceItemContent, {
                children: [
                    item.icon && /*#__PURE__*/ jsx(ApIcon, {
                        variant: "outlined",
                        name: item.icon,
                        size: apollo_core.Icon.IconXs
                    }),
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: fontToken,
                        style: ellipsisStyle,
                        children: item.displayName
                    })
                ]
            }),
            isCategory && /*#__PURE__*/ jsx(ApIcon, {
                variant: "outlined",
                name: "chevron_right",
                size: apollo_core.Icon.IconXs
            })
        ]
    });
    if (!tooltipContent) return menuItem;
    return /*#__PURE__*/ jsx(AutopilotChatTooltip, {
        title: /*#__PURE__*/ jsx(ApTypography, {
            color: 'var(--color-foreground-inverse)',
            variant: FontVariantToken.fontSizeS,
            children: tooltipContent
        }),
        placement: tooltipPlacement,
        open: isKeyboardSelected ? true : void 0,
        enterDelay: isKeyboardSelected ? 0 : CHAT_RESOURCE_PICKER_TOOLTIP_ENTER_DELAY,
        enterNextDelay: isKeyboardSelected ? 0 : CHAT_RESOURCE_PICKER_TOOLTIP_ENTER_DELAY,
        children: menuItem
    });
};
const chat_input_resource_picker_MenuContent = /*#__PURE__*/ react.memo(function({ virtualListRef, selectedIndex, navigationMode, onMouseEnterItem, onItemClick }) {
    const { displayedItems: items, drillDown, query, loading, loadingMore, searchInProgress, hasMore, error, previousDisplayCount, goBackOrClose, retryLoad, loadMore } = useAutopilotChatResourcePicker();
    const { theming, spacing } = useChatState();
    const { _ } = useLingui();
    const drillDownHeaderRef = useRef(null);
    const [drillDownHeaderHeight, setDrillDownHeaderHeight] = useState(0);
    useLayoutEffect(()=>{
        if (!drillDown) return void setDrillDownHeaderHeight(0);
        setDrillDownHeaderHeight(drillDownHeaderRef.current?.offsetHeight ?? 0);
    }, [
        drillDown
    ]);
    const handleRowsRendered = useCallback((visibleRows, _allRows)=>{
        if (!hasMore || loadingMore) return;
        if (visibleRows.stopIndex >= items.length - CHAT_RESOURCE_PICKER_LOAD_MORE_THRESHOLD) loadMore();
    }, [
        items.length,
        hasMore,
        loadingMore,
        loadMore
    ]);
    const tooltipPlacement = theming?.chatMenu?.groupItemTooltipPlacement ?? 'left';
    const isLoadingState = loading || searchInProgress;
    const skeletonElements = useMemo(()=>{
        const skeletonCount = Math.min(Math.max(previousDisplayCount, CHAT_RESOURCE_PICKER_MIN_SKELETON_COUNT), CHAT_RESOURCE_PICKER_MAX_SKELETON_COUNT);
        return Array.from({
            length: skeletonCount
        }).map((_, index)=>/*#__PURE__*/ jsx(SkeletonItem, {
                disabled: true,
                children: /*#__PURE__*/ jsx(ApSkeleton, {})
            }, `skeleton-${index}`));
    }, [
        previousDisplayCount
    ]);
    const rowCount = items.length + (loadingMore ? 1 : 0);
    const listHeight = Math.min(CHAT_RESOURCE_PICKER_MENU_MAX_HEIGHT - drillDownHeaderHeight, rowCount * CHAT_RESOURCE_PICKER_ITEM_HEIGHT);
    const rowProps = useMemo(()=>({
            items,
            selectedIndex,
            navigationMode,
            handleItemClick: onItemClick,
            onMouseEnterItem,
            tooltipPlacement,
            fontToken: spacing.primaryFontToken
        }), [
        items,
        selectedIndex,
        navigationMode,
        onItemClick,
        onMouseEnterItem,
        tooltipPlacement,
        spacing.primaryFontToken
    ]);
    const drillDownHeader = drillDown ? /*#__PURE__*/ jsxs(DrillDownHeader, {
        ref: drillDownHeaderRef,
        children: [
            /*#__PURE__*/ jsx(AutopilotChatIconButton, {
                size: "small",
                onClick: goBackOrClose,
                "aria-label": _({
                    id: 'autopilot-chat.resource-picker.back'
                }),
                children: /*#__PURE__*/ jsx(ApIcon, {
                    variant: "outlined",
                    name: "arrow_back",
                    size: apollo_core.Icon.IconXs
                })
            }),
            /*#__PURE__*/ jsx(ApTypography, {
                variant: spacing.primaryBoldFontToken,
                style: ellipsisStyle,
                children: drillDown.category.displayName
            })
        ]
    }) : null;
    if (isLoadingState) return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            drillDownHeader,
            skeletonElements
        ]
    });
    if (error) return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            drillDownHeader,
            /*#__PURE__*/ jsxs(ErrorContainer, {
                children: [
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: FontVariantToken.fontSizeS,
                        children: error
                    }),
                    /*#__PURE__*/ jsx(ApButton, {
                        variant: "text",
                        size: "small",
                        onClick: retryLoad,
                        label: _({
                            id: 'autopilot-chat.resource-picker.retry'
                        })
                    })
                ]
            })
        ]
    });
    if (0 === items.length) {
        const emptyMessage = query.trim() ? _({
            id: 'autopilot-chat.resource-picker.no-results'
        }) : _({
            id: 'autopilot-chat.resource-picker.empty'
        });
        return /*#__PURE__*/ jsxs(Fragment, {
            children: [
                drillDownHeader,
                /*#__PURE__*/ jsx(EmptyContainer, {
                    children: /*#__PURE__*/ jsx(ApTypography, {
                        variant: FontVariantToken.fontSizeS,
                        children: emptyMessage
                    })
                })
            ]
        });
    }
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            drillDownHeader,
            /*#__PURE__*/ jsx(StyledResourceList, {
                listRef: virtualListRef,
                rowProps: rowProps,
                rowComponent: VirtualizedResourceRow,
                rowCount: rowCount,
                rowHeight: CHAT_RESOURCE_PICKER_ITEM_HEIGHT,
                overscanCount: 5,
                onRowsRendered: handleRowsRendered,
                style: {
                    height: listHeight
                }
            })
        ]
    });
});
function ResourcePickerDropdownInner(_props, ref) {
    const { isOpen, isOpenRef, anchorPosition, displayedItems: items, drillDown, query, handleItemClick, close, goBackOrClose } = useAutopilotChatResourcePicker();
    const virtualListRef = useListRef(null);
    const { _ } = useLingui();
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [navigationMode, setNavigationMode] = useState('none');
    const prevStateRef = useRef({
        query,
        drillDownId: drillDown?.category?.id
    });
    useEffect(()=>{
        const prev = prevStateRef.current;
        const currentDrillDownId = drillDown?.category?.id;
        if (prev.query !== query || prev.drillDownId !== currentDrillDownId) {
            setSelectedIndex(0);
            setNavigationMode('none');
        }
        prev.query = query;
        prev.drillDownId = currentDrillDownId;
    }, [
        query,
        drillDown
    ]);
    useEffect(()=>{
        if (isOpen) {
            setSelectedIndex(0);
            setNavigationMode('none');
        }
    }, [
        isOpen
    ]);
    useEffect(()=>{
        if ('keyboard' === navigationMode) virtualListRef.current?.scrollToRow({
            index: selectedIndex,
            align: 'auto'
        });
    }, [
        selectedIndex,
        navigationMode,
        virtualListRef
    ]);
    const navigateUp = useCallback(()=>{
        setSelectedIndex((prev)=>Math.max(prev - 1, 0));
        setNavigationMode('keyboard');
    }, []);
    const navigateDown = useCallback(()=>{
        setSelectedIndex((prev)=>Math.min(prev + 1, items.length - 1));
        setNavigationMode('keyboard');
    }, [
        items.length
    ]);
    const handleMouseEnterItem = useCallback((index)=>{
        setSelectedIndex(index);
        setNavigationMode('pointer');
    }, []);
    const selectItem = useCallback(()=>{
        const selectedItem = items[selectedIndex];
        if (selectedItem) handleItemClick(selectedItem);
    }, [
        items,
        selectedIndex,
        handleItemClick
    ]);
    useImperativeHandle(ref, ()=>({
            handleKeyDown: (event)=>{
                if (!isOpenRef.current) return false;
                switch(event.key){
                    case 'ArrowDown':
                        event.preventDefault();
                        navigateDown();
                        return true;
                    case 'ArrowUp':
                        event.preventDefault();
                        navigateUp();
                        return true;
                    case 'Enter':
                    case 'Tab':
                        event.preventDefault();
                        selectItem();
                        return true;
                    case 'Escape':
                        event.preventDefault();
                        drillDown ? goBackOrClose() : close();
                        return true;
                    default:
                        return false;
                }
            }
        }), [
        navigateDown,
        navigateUp,
        selectItem,
        goBackOrClose,
        drillDown,
        close
    ]);
    const handleMenuClose = useCallback((_event, reason)=>{
        if ('escapeKeyDown' === reason && drillDown) return void goBackOrClose();
        close();
    }, [
        drillDown,
        goBackOrClose,
        close
    ]);
    return /*#__PURE__*/ jsx(Menu, {
        open: isOpen,
        anchorReference: "anchorPosition",
        anchorPosition: anchorPosition ?? void 0,
        onClose: handleMenuClose,
        anchorOrigin: {
            vertical: 'top',
            horizontal: 'left'
        },
        transformOrigin: {
            vertical: 'bottom',
            horizontal: 'left'
        },
        disableAutoFocus: true,
        autoFocus: false,
        MenuListProps: {
            'aria-label': _({
                id: 'autopilot-chat.resource-picker.label'
            }),
            dense: true,
            disableListWrap: true,
            onMouseDown: preventDefaultMouseDown
        },
        slotProps: MENU_SLOT_PROPS,
        children: /*#__PURE__*/ jsx(chat_input_resource_picker_MenuContent, {
            virtualListRef: virtualListRef,
            selectedIndex: selectedIndex,
            navigationMode: navigationMode,
            onMouseEnterItem: handleMouseEnterItem,
            onItemClick: handleItemClick
        })
    });
}
const ResourcePickerDropdown = /*#__PURE__*/ react.memo(/*#__PURE__*/ forwardRef(ResourcePickerDropdownInner));
export { ResourcePickerDropdown };
