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 } from "react";
import { useCanvasTheme } from "../BaseCanvas/CanvasThemeContext.js";
import { CanvasTooltip } from "../CanvasTooltip.js";
import { IconContainer, ListItemButton, SectionHeader, StyledList } from "./ListView.styles.js";
const DEFAULT_SKELETON_COUNT = 3;
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'
        });
    };
    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)result.push({
        type: 'item',
        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
        });
        for (const item of itemsBySection.get(sectionName) ?? [])result.push({
            type: 'item',
            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: 0,
            paddingRight: '4px',
            height: '32px',
            outlineOffset: '-1px'
        }), [
        style
    ]);
    const handleButtonClick = useCallback(()=>{
        const clickTarget = renderedItems[index];
        if (clickTarget?.type === 'item') onItemClick(clickTarget.item, index);
    }, [
        onItemClick,
        renderedItems,
        index
    ]);
    const handleButtonHover = useCallback(()=>{
        const hoverTarget = renderedItems[index];
        if (hoverTarget?.type === 'item') onItemHover?.(hoverTarget.item);
    }, [
        onItemHover,
        renderedItems,
        index
    ]);
    if ('section' === renderItem.type) return /*#__PURE__*/ jsx(SectionHeader, {
        ...ariaAttributes,
        style: style,
        children: /*#__PURE__*/ jsx("span", {
            className: "text-xs",
            children: renderItem.sectionName
        })
    });
    if ('skeleton' === renderItem.type) return /*#__PURE__*/ jsx("div", {
        style: style,
        children: /*#__PURE__*/ jsx(ListItemSkeleton, {})
    });
    const item = renderItem.item;
    const bgColor = isDarkMode ? item.colorDark ?? item.color : item.color;
    const isActive = index === activeIndex;
    return /*#__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,
                color: "var(--canvas-foreground-emp)",
                "data-testid": "list-item-icon",
                children: [
                    item.icon?.url && /*#__PURE__*/ jsx("img", {
                        src: item.icon?.url,
                        alt: item.name,
                        style: {
                            width: 24,
                            height: 24
                        }
                    }),
                    item.icon?.name && /*#__PURE__*/ jsx(CanvasIcon, {
                        icon: item.icon.name,
                        size: 24
                    }),
                    item.icon?.Component && /*#__PURE__*/ jsx(item.icon.Component, {})
                ]
            }),
            /*#__PURE__*/ jsxs(Column, {
                flex: 1,
                overflow: "hidden",
                children: [
                    /*#__PURE__*/ jsx(CanvasTooltip, {
                        content: item.name,
                        placement: "right",
                        smartTooltip: true,
                        children: /*#__PURE__*/ jsx("span", {
                            className: "text-sm list-view-item-name",
                            children: item.name
                        })
                    }),
                    item.description && /*#__PURE__*/ jsx(CanvasTooltip, {
                        content: item.description,
                        placement: "right",
                        smartTooltip: true,
                        children: /*#__PURE__*/ jsx("span", {
                            className: "text-xs list-view-item-name text-foreground-muted",
                            children: item.description
                        })
                    })
                ]
            }),
            !!item.children && /*#__PURE__*/ jsx(CanvasIcon, {
                icon: "chevron-right",
                size: 20,
                color: "var(--canvas-foreground-de-emp)"
            })
        ]
    });
});
const ListItemSkeleton = ()=>/*#__PURE__*/ jsxs("div", {
        className: "flex items-center gap-2.5 h-8",
        role: "presentation",
        "aria-hidden": "true",
        "data-testid": "list-item-skeleton",
        children: [
            /*#__PURE__*/ jsx(Skeleton, {
                className: "h-8 w-8 shrink-0 rounded-lg"
            }),
            /*#__PURE__*/ jsxs("div", {
                className: "flex-1 space-y-1.5 min-w-0",
                children: [
                    /*#__PURE__*/ jsx(Skeleton, {
                        className: "h-3.5 w-1/3"
                    }),
                    /*#__PURE__*/ jsx(Skeleton, {
                        className: "h-3 w-2/3"
                    })
                ]
            })
        ]
    });
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
    ]);
    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: 40,
        overscanCount: 20,
        onScroll: onScroll
    });
});
const ListView_ListView = /*#__PURE__*/ memo(ListViewInner);
export { ListView_ListView as ListView, buildRenderedItems };
