import { jsx, jsxs } from "react/jsx-runtime";
import ChevronRight from "@mui/icons-material/ChevronRight";
import { Box, Tooltip } from "@mui/material";
import { styled } from "@mui/material/styles";
import { RichTreeView, TreeItem } from "@mui/x-tree-view";
import { useTreeItemModel, useTreeItemUtils } from "@mui/x-tree-view/hooks";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import react, { createContext, useCallback, useContext, useMemo, useState } from "react";
import { ApTypography } from "../ap-typography/index.js";
import { deepFind, recursivelyExpand } from "./utils.js";
const ICON_SIZE = parseInt(apollo_core.Spacing.SpacingM, 10);
const CHEVRON_ICON_SIZE = ICON_SIZE;
const ICON_GAP = parseInt(apollo_core.Spacing.SpacingS, 10);
const StyledTreeItem = styled(TreeItem, {
    shouldForwardProp: (prop)=>'levelPadding' !== prop && 'disableExpandCollapse' !== prop
})(({ disableExpandCollapse })=>({
        '.MuiTreeItem-content': {
            position: 'relative',
            color: 'var(--color-foreground)',
            borderRadius: 0,
            height: apollo_core.Spacing.SpacingXl,
            '&.Mui-selected': {
                backgroundColor: 'var(--color-background-selected)',
                '&::before': {
                    content: '""',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    bottom: 0,
                    backgroundColor: 'var(--color-selection-indicator)',
                    width: apollo_core.Spacing.SpacingXs
                },
                '&:hover': {
                    backgroundColor: 'var(--color-background-selected)'
                }
            },
            '&:hover:not(.Mui-disabled)': {
                backgroundColor: 'var(--color-background-hover)'
            },
            '.MuiTreeItem-iconContainer': {
                display: disableExpandCollapse ? 'none' : 'flex',
                width: `${ICON_SIZE}px`,
                height: `${ICON_SIZE}px`,
                '& > svg': {
                    fontSize: `${ICON_SIZE}px !important`
                }
            }
        },
        '.MuiCollapse-root': {
            paddingLeft: 0,
            '.MuiTreeItem-content': {
                paddingLeft: 'var(--ap-tree-level-padding) !important'
            }
        },
        '&:focus-visible > .MuiTreeItem-content': {
            zIndex: 1,
            outline: `${apollo_core.Border.BorderThickS} solid var(--color-focus-indicator)`
        }
    }));
const ApTreeItemParentContext = /*#__PURE__*/ createContext({
    level: 0,
    hasIcon: false,
    levelPadding: 0
});
const ApTreeItem = ({ itemId, children, disableExpandCollapse, showSelectedChevron })=>{
    const item = useTreeItemModel(itemId);
    const { status, interactions } = useTreeItemUtils({
        itemId,
        children
    });
    const parentContext = useContext(ApTreeItemParentContext);
    const { id = itemId, title = '', description, icon, iconColor, disabled, children: descendants, additionalInfo, titleColor } = item || {};
    const canExpand = status.expandable;
    const isItemExpanded = status.expanded;
    const isItemSelected = status.selected;
    const canSelect = !status.disabled;
    const hasChildren = !!descendants?.length;
    const currentItemContext = useMemo(()=>{
        const level = parentContext.level + 1;
        return {
            level,
            levelPadding: parentContext.levelPadding + (level > 1 ? CHEVRON_ICON_SIZE + ICON_SIZE : 0) - (hasChildren ? 0 : CHEVRON_ICON_SIZE),
            hasIcon: Boolean(icon)
        };
    }, [
        parentContext,
        icon,
        hasChildren
    ]);
    const { levelPadding } = currentItemContext;
    const handleKeyDown = useCallback((e)=>{
        e.defaultMuiPrevented = true;
        if (e.currentTarget !== e.target) return;
        if (' ' === e.key && canSelect) {
            e.preventDefault();
            interactions.handleSelection(e);
        } else if ('Enter' === e.key) {
            if (canExpand) {
                interactions.handleExpansion(e);
                e.preventDefault();
            } else if (canSelect) {
                interactions.handleSelection(e);
                e.preventDefault();
            }
        } else if ('ArrowRight' === e.key) {
            if (!isItemExpanded) interactions.handleExpansion(e);
            e.preventDefault();
        } else if ('ArrowLeft' === e.key) {
            if (isItemExpanded) interactions.handleExpansion(e);
            e.preventDefault();
        }
    }, [
        canSelect,
        canExpand,
        interactions,
        isItemExpanded
    ]);
    const label = /*#__PURE__*/ jsx(Tooltip, {
        title: description || '',
        arrow: true,
        children: /*#__PURE__*/ jsxs(Box, {
            sx: {
                display: 'flex',
                width: '100%',
                alignItems: 'center',
                justifyContent: 'space-between'
            },
            children: [
                /*#__PURE__*/ jsxs(Box, {
                    sx: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: `${ICON_GAP}px`
                    },
                    children: [
                        icon && /*#__PURE__*/ jsx(Box, {
                            component: "span",
                            sx: {
                                display: 'inline-flex',
                                alignItems: 'center',
                                width: `${ICON_SIZE}px`,
                                height: `${ICON_SIZE}px`,
                                color: iconColor || 'inherit'
                            },
                            children: icon
                        }),
                        /*#__PURE__*/ jsx(ApTypography, {
                            variant: FontVariantToken.fontSizeM,
                            style: {
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                color: titleColor || void 0
                            },
                            children: title
                        })
                    ]
                }),
                /*#__PURE__*/ jsxs(Box, {
                    sx: {
                        display: 'flex',
                        alignItems: 'center',
                        gap: apollo_core.Spacing.SpacingXs
                    },
                    children: [
                        additionalInfo && /*#__PURE__*/ jsx(ApTypography, {
                            variant: FontVariantToken.fontSizeM,
                            style: {
                                color: 'var(--color-foreground-de-emp)',
                                whiteSpace: 'nowrap'
                            },
                            children: additionalInfo
                        }),
                        showSelectedChevron && isItemSelected && /*#__PURE__*/ jsx(ChevronRight, {
                            sx: {
                                fontSize: ICON_SIZE,
                                color: 'var(--color-foreground-de-emp)'
                            }
                        })
                    ]
                })
            ]
        })
    });
    return /*#__PURE__*/ jsx(ApTreeItemParentContext.Provider, {
        value: currentItemContext,
        children: /*#__PURE__*/ jsx(StyledTreeItem, {
            levelPadding: levelPadding,
            "data-is-focusable": !disabled,
            style: {
                '--ap-tree-level-padding': `${levelPadding}px`
            },
            onKeyDown: handleKeyDown,
            itemId: id,
            label: label,
            disableExpandCollapse: disableExpandCollapse,
            disabled: disabled,
            "data-test": `ap-tree-item-${id}`,
            role: "treeitem",
            children: children
        }, id)
    });
};
const getItemLabel = (item)=>item.title;
const isItemDisabled = (item)=>!!item.disabled;
const ApTreeView = /*#__PURE__*/ react.forwardRef(({ items = [], selectedItemId, expanded, disableExpandCollapse, showSelectedChevron, onSelectedItemsChange, useApIcon = false, ...restProps }, ref)=>{
    const [expandedItems, setExpandedItems] = useState(()=>expanded && 'boolean' == typeof expanded || disableExpandCollapse ? recursivelyExpand(items) : [
            ...expanded || []
        ]);
    const handleOnSelectedItemsChange = useCallback((_, itemId)=>{
        if (null == itemId) return void onSelectedItemsChange?.(void 0);
        const selectedItemResult = deepFind(items, (item)=>itemId === item.id);
        if (selectedItemResult) onSelectedItemsChange?.(selectedItemResult.id);
    }, [
        items,
        onSelectedItemsChange
    ]);
    const onExpandedItemsChange = useCallback((_e, itemIds)=>{
        if (disableExpandCollapse) return;
        setExpandedItems(itemIds);
    }, [
        disableExpandCollapse
    ]);
    return /*#__PURE__*/ jsx("div", {
        ref: ref,
        role: "tree",
        ...restProps,
        children: /*#__PURE__*/ jsx(RichTreeView, {
            items: items,
            selectedItems: selectedItemId ?? null,
            expandedItems: expandedItems,
            getItemLabel: getItemLabel,
            onSelectedItemsChange: handleOnSelectedItemsChange,
            onExpandedItemsChange: onExpandedItemsChange,
            isItemDisabled: isItemDisabled,
            slots: {
                item: ApTreeItem
            },
            slotProps: {
                item: {
                    disableExpandCollapse,
                    showSelectedChevron,
                    useApIcon
                }
            }
        })
    });
});
ApTreeView.displayName = 'ApTreeView';
export { ApTreeItem, ApTreeView };
