import { jsx, jsxs } from "react/jsx-runtime";
import { Column } from "../../layouts/index.js";
import { CanvasIcon, partition } from "../../utils/index.js";
import { Skeleton } from "@uipath/apollo-wind";
import { forwardRef, memo, useCallback, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useCanvasTheme } from "../BaseCanvas/CanvasThemeContext.js";
import { CanvasTooltip } from "../CanvasTooltip.js";
import { InitialsBadge } from "../shared/InitialsBadge.js";
import { IconContainer, ListItemButton, StyledList } from "./ListView.styles.js";
const DEFAULT_SKELETON_COUNT = 3;
const ROW_HEIGHT_ITEM = 32;
const ROW_HEIGHT_ITEM_TWO_LINE = 44;
const ROW_HEIGHT_SECTION = 30;
const ROW_HEIGHT_SECTION_FIRST = 22;
const ROW_HEIGHT_DIVIDER = 13;
function getRenderItemHeight(renderItem) {
    if (!renderItem) return ROW_HEIGHT_ITEM;
    switch(renderItem.type){
        case 'divider':
            return ROW_HEIGHT_DIVIDER;
        case 'section':
            return renderItem.first ? ROW_HEIGHT_SECTION_FIRST : ROW_HEIGHT_SECTION;
        case 'skeleton':
            return ROW_HEIGHT_ITEM;
        default:
            return renderItem.item.description ? ROW_HEIGHT_ITEM_TWO_LINE : ROW_HEIGHT_ITEM;
    }
}
function buildRenderedItems(items, enableSections, loadingSkeleton) {
    const result = [];
    const skeletonConfig = 'object' == typeof loadingSkeleton ? loadingSkeleton : loadingSkeleton ? {} : void 0;
    const baseSkeletonCount = skeletonConfig?.count ?? DEFAULT_SKELETON_COUNT;
    const pushSkeletons = (count)=>{
        for(let i = 0; i < count; i++)result.push({
            type: 'skeleton'
        });
    };
    const pushItem = (item)=>{
        if (item.dividerBefore && result.length > 0) result.push({
            type: 'divider'
        });
        result.push({
            type: 'item',
            item
        });
    };
    if (!enableSections) {
        for (const item of items)result.push({
            type: 'item',
            item
        });
        if (skeletonConfig && !skeletonConfig.sections) pushSkeletons(baseSkeletonCount);
        return result;
    }
    const [itemsWithSection, itemsWithoutSection] = partition(items, (item)=>!!item.section);
    for (const item of itemsWithoutSection)pushItem(item);
    const itemsBySection = new Map();
    for (const item of itemsWithSection){
        const name = item.section;
        const bucket = itemsBySection.get(name);
        if (bucket) bucket.push(item);
        else itemsBySection.set(name, [
            item
        ]);
    }
    const skeletonBySection = new Map(skeletonConfig?.sections?.map((s)=>[
            s.name,
            s
        ]) ?? []);
    const sectionNames = [
        ...itemsBySection.keys()
    ];
    for (const s of skeletonConfig?.sections ?? [])if (!itemsBySection.has(s.name)) sectionNames.push(s.name);
    for (const sectionName of sectionNames){
        result.push({
            type: 'section',
            sectionName,
            first: 0 === result.length
        });
        for (const item of itemsBySection.get(sectionName) ?? [])pushItem(item);
        const skeletonForSection = skeletonBySection.get(sectionName);
        if (skeletonForSection) pushSkeletons(skeletonForSection.count ?? baseSkeletonCount);
    }
    if (skeletonConfig && !skeletonConfig.sections) pushSkeletons(baseSkeletonCount);
    return result;
}
const IconContainerMemoized = /*#__PURE__*/ memo(IconContainer);
const ListViewRow = /*#__PURE__*/ memo(({ index, style, ariaAttributes, renderedItems, activeIndex, isLoading, isDarkMode, onItemClick, onItemHover })=>{
    const renderItem = renderedItems[index];
    const buttonStyle = useMemo(()=>({
            ...style,
            padding: '4px 6px'
        }), [
        style
    ]);
    const nameRef = useRef(null);
    const descriptionRef = useRef(null);
    const [truncated, setTruncated] = useState({
        name: false,
        description: false
    });
    const measureTruncation = useCallback(()=>{
        const n = nameRef.current;
        const d = descriptionRef.current;
        const next = {
            name: !!n && n.scrollWidth > n.clientWidth,
            description: !!d && d.scrollWidth > d.clientWidth
        };
        setTruncated((prev)=>prev.name === next.name && prev.description === next.description ? prev : next);
    }, []);
    const handleButtonClick = useCallback(()=>{
        const clickTarget = renderedItems[index];
        if (clickTarget?.type === 'item') onItemClick(clickTarget.item, index);
    }, [
        onItemClick,
        renderedItems,
        index
    ]);
    const handleButtonHover = useCallback(()=>{
        measureTruncation();
        const hoverTarget = renderedItems[index];
        if (hoverTarget?.type === 'item') onItemHover?.(hoverTarget.item);
    }, [
        measureTruncation,
        onItemHover,
        renderedItems,
        index
    ]);
    if ('section' === renderItem.type) return /*#__PURE__*/ jsx("div", {
        role: "presentation",
        style: style,
        className: `flex items-end box-border ${renderItem.first ? 'px-2 py-1' : 'px-2 pt-3 pb-1'}`,
        "data-testid": "list-section-header",
        children: /*#__PURE__*/ jsx("span", {
            className: "uppercase text-foreground-muted font-bold text-xs",
            children: renderItem.sectionName
        })
    });
    if ('skeleton' === renderItem.type) return /*#__PURE__*/ jsx("div", {
        style: style,
        children: /*#__PURE__*/ jsx(ListItemSkeleton, {})
    });
    if ('divider' === renderItem.type) return /*#__PURE__*/ jsx("div", {
        role: "presentation",
        "aria-hidden": "true",
        "data-testid": "list-item-divider",
        style: style,
        className: "flex items-center box-border px-1.5",
        children: /*#__PURE__*/ jsx("div", {
            className: "w-full border-t border-border-de-emp"
        })
    });
    const item = renderItem.item;
    const bgColor = isDarkMode ? item.colorDark ?? item.color : item.color;
    const isActive = index === activeIndex;
    const button = /*#__PURE__*/ jsxs(ListItemButton, {
        ...ariaAttributes,
        tabIndex: -1,
        id: `toolbox-item-${item.id}`,
        role: "option",
        "aria-selected": isActive,
        style: buttonStyle,
        onClick: handleButtonClick,
        onHoverStart: handleButtonHover,
        className: `${isLoading ? 'loading' : ''} ${isActive ? 'active' : ''}`,
        disabled: isLoading,
        children: [
            /*#__PURE__*/ jsxs(IconContainerMemoized, {
                bgColor: bgColor,
                style: item.contentColor ? {
                    color: item.contentColor
                } : void 0,
                "data-testid": "list-item-icon",
                children: [
                    item.icon?.url && /*#__PURE__*/ jsx("img", {
                        src: item.icon?.url,
                        alt: item.name,
                        className: "w-5 h-5"
                    }),
                    item.icon?.name && /*#__PURE__*/ jsx(CanvasIcon, {
                        icon: item.icon.name,
                        size: 20
                    }),
                    item.icon?.Component && /*#__PURE__*/ jsx(item.icon.Component, {}),
                    !item.icon?.url && !item.icon?.name && !item.icon?.Component && /*#__PURE__*/ jsx(InitialsBadge, {
                        name: item.name,
                        size: "20px",
                        "data-testid": "list-item-initials-badge"
                    })
                ]
            }),
            /*#__PURE__*/ jsxs(Column, {
                flex: 1,
                overflow: "hidden",
                children: [
                    /*#__PURE__*/ jsx("span", {
                        ref: nameRef,
                        className: "text-sm list-view-item-name",
                        style: item.contentColor ? {
                            color: item.contentColor
                        } : void 0,
                        children: item.name
                    }),
                    item.description && /*#__PURE__*/ jsx("span", {
                        ref: descriptionRef,
                        className: "text-xs list-view-item-name text-foreground-muted",
                        children: item.description
                    })
                ]
            }),
            item.badge && /*#__PURE__*/ jsx("span", {
                className: "shrink-0 uppercase font-semibold text-[10px] py-px px-1 rounded border border-border text-foreground-muted",
                "data-testid": "list-item-badge",
                children: item.badge
            }),
            item.trailingIcon && !item.children && /*#__PURE__*/ jsx("span", {
                "data-testid": "list-item-trailing-icon",
                className: "flex shrink-0",
                children: /*#__PURE__*/ jsx(CanvasIcon, {
                    icon: item.trailingIcon.name,
                    size: 16,
                    color: item.trailingIcon.color ?? 'var(--canvas-foreground-de-emp)'
                })
            }),
            !!item.children && /*#__PURE__*/ jsx(CanvasIcon, {
                icon: "chevron-right",
                size: 16,
                color: "var(--canvas-foreground-de-emp)"
            })
        ]
    });
    const showName = truncated.name;
    const showDescription = !!item.description && truncated.description;
    const showPopover = truncated.name || truncated.description || !!item.detail;
    const popover = showPopover ? /*#__PURE__*/ jsxs("div", {
        className: "flex flex-col gap-0.5",
        children: [
            showName && /*#__PURE__*/ jsx("span", {
                className: "text-sm",
                children: item.name
            }),
            showDescription && /*#__PURE__*/ jsx("span", {
                className: "text-xs text-foreground-muted",
                children: item.description
            }),
            item.detail && /*#__PURE__*/ jsx("span", {
                className: "text-xs",
                children: item.detail
            })
        ]
    }) : null;
    return /*#__PURE__*/ jsx(CanvasTooltip, {
        content: popover,
        placement: "right",
        delay: true,
        contentClassName: "max-w-64",
        hide: !showPopover,
        disableSkipDelay: true,
        children: button
    }, item.id);
});
const ListItemSkeleton = ()=>/*#__PURE__*/ jsxs("div", {
        className: "flex items-center gap-2.5 h-8 px-1.5",
        role: "presentation",
        "aria-hidden": "true",
        "data-testid": "list-item-skeleton",
        children: [
            /*#__PURE__*/ jsx(Skeleton, {
                className: "h-6 w-6 shrink-0 rounded-md"
            }),
            /*#__PURE__*/ jsx(Skeleton, {
                className: "h-3.5 w-1/2"
            })
        ]
    });
const ListViewInner = /*#__PURE__*/ forwardRef(function({ items, activeIndex = -1, listRef, onItemClick, onItemHover, onScroll, emptyStateMessage = 'No items found', emptyStateIcon = 'search-x', renderEmptyState, isLoading = false, enableSections = true, loadingSkeleton }, ref) {
    const { isDarkMode } = useCanvasTheme();
    const activeSkeleton = loadingSkeleton ?? (isLoading && 0 === items.length ? true : void 0);
    const renderedItems = useMemo(()=>buildRenderedItems(items, enableSections, activeSkeleton), [
        items,
        enableSections,
        activeSkeleton
    ]);
    useImperativeHandle(ref, ()=>({
            renderedItems
        }), [
        renderedItems
    ]);
    const rowProps = useMemo(()=>({
            renderedItems,
            activeIndex,
            isLoading,
            isDarkMode,
            onItemClick,
            onItemHover
        }), [
        renderedItems,
        activeIndex,
        isLoading,
        isDarkMode,
        onItemClick,
        onItemHover
    ]);
    const getRowHeight = useCallback((index)=>getRenderItemHeight(renderedItems[index]), [
        renderedItems
    ]);
    if (0 === renderedItems.length) {
        if (renderEmptyState) return renderEmptyState();
        return /*#__PURE__*/ jsxs(Column, {
            align: "center",
            justify: "center",
            flex: 1,
            gap: 10,
            style: {
                minHeight: '250px'
            },
            children: [
                /*#__PURE__*/ jsx(CanvasIcon, {
                    icon: emptyStateIcon,
                    size: 48,
                    color: "var(--canvas-foreground-de-emp)"
                }),
                /*#__PURE__*/ jsx("span", {
                    className: "text-xs text-foreground-muted",
                    children: emptyStateMessage
                })
            ]
        });
    }
    return /*#__PURE__*/ jsx(StyledList, {
        id: "toolbox-listbox",
        role: "listbox",
        "aria-busy": activeSkeleton ? true : void 0,
        listRef: listRef,
        rowProps: rowProps,
        rowComponent: ListViewRow,
        rowCount: renderedItems.length,
        rowHeight: getRowHeight,
        overscanCount: 20,
        onScroll: onScroll
    });
});
const ListView_ListView = /*#__PURE__*/ memo(ListViewInner);
export { ListView_ListView as ListView, ROW_HEIGHT_DIVIDER, ROW_HEIGHT_ITEM, ROW_HEIGHT_ITEM_TWO_LINE, ROW_HEIGHT_SECTION, ROW_HEIGHT_SECTION_FIRST, buildRenderedItems, getRenderItemHeight };
