import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import Add from "@mui/icons-material/Add";
import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import CircularProgress from "@mui/material/CircularProgress";
import Typography from "@mui/material/Typography";
import { Colors, FontFamily } from "@uipath/apollo-core";
import react from "react";
import { useSafeLingui } from "../../../i18n/index.js";
import { FolderSwitcher } from "./primitives/FolderSwitcher.js";
import { defaultRowActions } from "./primitives/ModelOptionRow.js";
import { GroupedOptionList, VirtualOptionList, optionDomId } from "./primitives/OptionList.js";
import { PickerPopup } from "./primitives/PickerPopup.js";
import { PickerSearchInput } from "./primitives/PickerSearchInput.js";
import { PickerTrigger } from "./primitives/PickerTrigger.js";
import { useModelPickerState } from "./useModelPickerState.js";
import { buildLlmConfigurationsUrl, platformNavigation, useCanManageByo, useUserFolders } from "./usePlatformAccess.js";
const REQUIRED_INDICATOR = '*';
const AUTO_VIRTUALIZE_THRESHOLD = 120;
const ModelPicker = /*#__PURE__*/ react.forwardRef(({ models, value, onChange, label, required, placeholder, disabled, invalid, errorText, variant = 'searchable', groupBy = "subscription", allowGroupingChange = true, homeRegion, recommendedModelIds, previewModelIds, filter, badgesFor, customTagsFor, customTagVariants, canManageByo, onUseCustomModel, requestContext, enableFolders = false, folders, folder = null, onFolderChange, allFoldersLabel, loading, error, showGroupHeaders = true, slots }, forwardedRef)=>{
    const { _ } = useSafeLingui();
    const i18n = react.useMemo(()=>({
            _
        }), [
        _
    ]);
    const resolvedLabel = label ?? _({
        id: 'modelPicker.label.default',
        message: 'Model'
    });
    const resolvedPlaceholder = placeholder ?? _({
        id: 'modelPicker.placeholder.selectAModel',
        message: 'Select a model'
    });
    const initiallyCollapsedGroups = react.useMemo(()=>[], []);
    const state = useModelPickerState({
        models,
        value,
        onChange,
        groupBy,
        recommendedModelIds,
        previewModelIds,
        filter,
        initiallyCollapsedGroups,
        i18n
    });
    const { open, setOpen, query, setQuery, groupBy: activeGroupBy, setGroupBy, filtered, groupCounts, collapsedGroups, toggleGroup, selected, unknownValue, activeIndex, setActiveIndex, onSearchKeyDown, choose, id, triggerRef, searchRef } = state;
    const listboxId = `${id}-listbox`;
    const List = 'virtualized' === variant || filtered.length > AUTO_VIRTUALIZE_THRESHOLD ? VirtualOptionList : GroupedOptionList;
    const handleTriggerRef = react.useCallback((node)=>{
        triggerRef.current = node;
        if ('function' == typeof forwardedRef) forwardedRef(node);
        else if (forwardedRef) forwardedRef.current = node;
    }, [
        forwardedRef,
        triggerRef
    ]);
    const closePopup = react.useCallback(()=>setOpen(false), [
        setOpen
    ]);
    const slotCtx = react.useMemo(()=>({
            selected,
            close: closePopup
        }), [
        selected,
        closePopup
    ]);
    const { canManage: isOrgAdmin } = useCanManageByo(void 0 === canManageByo && requestContext ? requestContext : null);
    const effectiveCanManageByo = canManageByo ?? isOrgAdmin ?? false;
    const { folders: fetchedFolders } = useUserFolders(enableFolders && !folders && requestContext ? requestContext : null);
    const effectiveFolders = folders ?? (enableFolders ? fetchedFolders : void 0);
    const selectedFolderNumericId = react.useMemo(()=>effectiveFolders?.find((f)=>f.id === folder)?.numericId, [
        effectiveFolders,
        folder
    ]);
    const navigateToLlmConfigurations = react.useMemo(()=>{
        if (!requestContext) return;
        return (link)=>{
            platformNavigation.assign(buildLlmConfigurationsUrl(requestContext, {
                ...link,
                folderNumericId: selectedFolderNumericId
            }));
        };
    }, [
        requestContext,
        selectedFolderNumericId
    ]);
    react.useEffect(()=>{
        if ("u" < typeof process || 'production' === process.env['NODE_ENV'] || !effectiveFolders) return;
        const seen = new Set();
        for (const f of effectiveFolders){
            if (seen.has(f.id)) return void console.warn(`[ModelPicker] Duplicate folder id "${f.id}" — folder selection will misbehave.`);
            seen.add(f.id);
        }
    }, [
        effectiveFolders
    ]);
    const tagContext = react.useMemo(()=>({
            i18n,
            homeRegion,
            recommendedModelIds,
            previewModelIds,
            badgesFor,
            customTagsFor
        }), [
        i18n,
        homeRegion,
        recommendedModelIds,
        previewModelIds,
        badgesFor,
        customTagsFor
    ]);
    const rowHideTagKinds = react.useMemo(()=>"subscription" === activeGroupBy ? [
            'recommended',
            'preview'
        ] : void 0, [
        activeGroupBy
    ]);
    const renderRowActions = react.useMemo(()=>{
        if (slots?.optionActions) return slots.optionActions;
        if (!effectiveCanManageByo || !navigateToLlmConfigurations) return ()=>null;
        return (m)=>defaultRowActions(m, {
                i18n,
                onEdit: (model)=>navigateToLlmConfigurations({
                        intent: 'edit',
                        configurationId: model.byomDetails?.productLlmConfigurationId
                    })
            });
    }, [
        slots?.optionActions,
        effectiveCanManageByo,
        navigateToLlmConfigurations,
        i18n
    ]);
    const footerNode = react.useMemo(()=>{
        if (slots && Object.hasOwn(slots, 'popupFooter')) return slots.popupFooter ? slots.popupFooter(slotCtx) : null;
        if (!effectiveCanManageByo) return null;
        const activate = onUseCustomModel ?? (navigateToLlmConfigurations ? ()=>navigateToLlmConfigurations({
                intent: 'add'
            }) : void 0);
        return /*#__PURE__*/ jsx(UseCustomModelFooter, {
            onActivate: ()=>{
                closePopup();
                activate?.();
            },
            disabled: !activate
        });
    }, [
        slots,
        effectiveCanManageByo,
        onUseCustomModel,
        navigateToLlmConfigurations,
        slotCtx,
        closePopup
    ]);
    return /*#__PURE__*/ jsxs(Box, {
        className: "apollo-model-picker",
        sx: {
            width: '100%',
            fontFamily: FontFamily.FontNormal
        },
        children: [
            /*#__PURE__*/ jsxs(Typography, {
                component: "label",
                htmlFor: `${id}-trigger`,
                sx: {
                    display: 'block',
                    fontSize: 13,
                    fontWeight: 600,
                    color: `var(--color-foreground-de-emp, ${Colors.ColorGray550})`,
                    mb: 0.875
                },
                children: [
                    resolvedLabel,
                    required && /*#__PURE__*/ jsx(Box, {
                        component: "span",
                        "aria-hidden": true,
                        sx: {
                            color: `var(--color-error-text, ${Colors.ColorRed700})`,
                            ml: 0.25
                        },
                        children: REQUIRED_INDICATOR
                    })
                ]
            }),
            /*#__PURE__*/ jsx(PickerTrigger, {
                id: `${id}-trigger`,
                triggerRef: handleTriggerRef,
                selected: selected,
                unknownValue: unknownValue,
                placeholder: resolvedPlaceholder,
                disabled: disabled,
                invalid: !!invalid || !!error || !!unknownValue,
                required: required,
                open: open,
                controlsId: listboxId,
                describedById: errorText ?? error ? `${id}-error` : void 0,
                tagContext: tagContext,
                tagVariants: customTagVariants,
                extra: slots?.triggerExtra?.(selected),
                onClick: ()=>setOpen(!open)
            }),
            (errorText ?? error) && /*#__PURE__*/ jsx(Typography, {
                id: `${id}-error`,
                variant: "caption",
                role: "alert",
                sx: {
                    display: 'block',
                    color: `var(--color-error-text, ${Colors.ColorRed700})`,
                    mt: 0.5,
                    fontSize: 12
                },
                children: errorText ?? error?.message
            }),
            /*#__PURE__*/ jsxs(PickerPopup, {
                open: open,
                anchorEl: triggerRef.current,
                onClose: closePopup,
                header: /*#__PURE__*/ jsxs(Fragment, {
                    children: [
                        slots?.popupHeader?.(),
                        /*#__PURE__*/ jsx(PickerSearchInput, {
                            value: query,
                            onChange: (next)=>{
                                setQuery(next);
                                setActiveIndex(0);
                            },
                            onKeyDown: onSearchKeyDown,
                            inputRef: searchRef,
                            listboxId: listboxId,
                            activeDescendantId: filtered[activeIndex] ? optionDomId(listboxId, filtered[activeIndex].modelId) : void 0,
                            leading: slots?.searchLeading?.() ?? (effectiveFolders && effectiveFolders.length > 0 && onFolderChange ? /*#__PURE__*/ jsx(FolderSwitcher, {
                                folders: effectiveFolders,
                                value: folder ?? null,
                                onChange: onFolderChange,
                                allFoldersLabel: allFoldersLabel
                            }) : void 0),
                            trailing: allowGroupingChange ? /*#__PURE__*/ jsx(GroupBySegmented, {
                                value: activeGroupBy,
                                onChange: setGroupBy
                            }) : void 0
                        })
                    ]
                }),
                footer: footerNode,
                children: [
                    loading && /*#__PURE__*/ jsx(Box, {
                        role: "status",
                        "aria-live": "polite",
                        "aria-label": _({
                            id: 'modelPicker.loading.label',
                            message: 'Loading models'
                        }),
                        sx: {
                            py: 3,
                            display: 'flex',
                            justifyContent: 'center',
                            color: `var(--color-foreground-de-emp, ${Colors.ColorGray550})`
                        },
                        children: /*#__PURE__*/ jsx(CircularProgress, {
                            size: 20
                        })
                    }),
                    error && !loading && /*#__PURE__*/ jsx(Box, {
                        role: "alert",
                        sx: {
                            py: 2,
                            px: 2,
                            textAlign: 'center',
                            color: `var(--color-error-text, ${Colors.ColorRed700})`,
                            fontSize: 13
                        },
                        children: error.message
                    }),
                    !loading && !error && 0 === filtered.length && /*#__PURE__*/ jsx(Box, {
                        role: "status",
                        "aria-live": "polite",
                        sx: {
                            py: 3,
                            textAlign: 'center',
                            color: `var(--color-foreground-de-emp, ${Colors.ColorGray550})`,
                            fontSize: 13
                        },
                        children: query.trim() ? _({
                            id: 'modelPicker.empty.noMatch',
                            message: 'No models match "{query}".',
                            values: {
                                query: query.trim()
                            }
                        }) : _({
                            id: 'modelPicker.empty.noModels',
                            message: 'No models available.'
                        })
                    }),
                    /*#__PURE__*/ jsx(Box, {
                        "aria-live": "polite",
                        "aria-atomic": "true",
                        sx: {
                            position: 'absolute',
                            width: '1px',
                            height: '1px',
                            margin: '-1px',
                            padding: 0,
                            overflow: 'hidden',
                            clip: 'rect(0 0 0 0)',
                            whiteSpace: 'nowrap',
                            border: 0
                        },
                        children: loading || error || !(filtered.length > 0) ? '' : 1 === filtered.length ? _({
                            id: 'modelPicker.count.one',
                            message: '{n} model',
                            values: {
                                n: filtered.length
                            }
                        }) : _({
                            id: 'modelPicker.count.many',
                            message: '{n} models',
                            values: {
                                n: filtered.length
                            }
                        })
                    }),
                    !loading && !error && filtered.length > 0 && /*#__PURE__*/ jsxs(Fragment, {
                        children: [
                            /*#__PURE__*/ jsx(List, {
                                id: listboxId,
                                options: filtered,
                                activeIndex: activeIndex,
                                setActiveIndex: setActiveIndex,
                                selectedId: value ?? null,
                                onSelect: choose,
                                tagContext: tagContext,
                                tagVariants: customTagVariants,
                                groupCounts: groupCounts,
                                collapsedGroups: collapsedGroups,
                                onGroupToggle: toggleGroup,
                                hideGroupHeaders: !showGroupHeaders || 'flat' === activeGroupBy,
                                hideTagKinds: rowHideTagKinds,
                                renderRowActions: renderRowActions,
                                renderRowMeta: slots?.optionMeta
                            }),
                            slots?.listFooter?.(slotCtx)
                        ]
                    })
                ]
            })
        ]
    });
});
ModelPicker.displayName = 'ModelPicker';
const GroupBySegmented = ({ value, onChange })=>{
    const { _ } = useSafeLingui();
    const groupByOptions = [
        {
            key: "subscription",
            label: _({
                id: 'modelPicker.groupBy.category',
                message: 'Category'
            })
        },
        {
            key: 'vendor',
            label: _({
                id: 'modelPicker.groupBy.provider',
                message: 'Provider'
            })
        }
    ];
    return /*#__PURE__*/ jsx(Box, {
        role: "group",
        "aria-label": _({
            id: 'modelPicker.groupBy.ariaLabel',
            message: 'Group models by'
        }),
        sx: {
            display: 'inline-flex',
            backgroundColor: `var(--color-background-secondary, ${Colors.ColorGray150})`,
            borderRadius: '8px',
            p: '3px',
            gap: '3px'
        },
        children: groupByOptions.map((opt)=>{
            const active = opt.key === value;
            return /*#__PURE__*/ jsx(ButtonBase, {
                onClick: ()=>onChange(opt.key),
                "aria-pressed": active,
                sx: {
                    fontSize: 12.5,
                    fontWeight: 600,
                    lineHeight: 1.2,
                    px: 1.25,
                    py: 0.625,
                    borderRadius: '6px',
                    color: active ? `var(--color-primary, ${Colors.ColorBlue500})` : `var(--color-foreground-de-emp, ${Colors.ColorGray550})`,
                    backgroundColor: active ? `var(--color-background-raised, ${Colors.ColorWhite})` : 'transparent',
                    boxShadow: active ? '0 1px 2px rgba(16, 24, 40, 0.14)' : 'none',
                    transition: 'background-color 120ms, color 120ms, box-shadow 120ms',
                    '&:hover': {
                        backgroundColor: active ? `var(--color-background-raised, ${Colors.ColorWhite})` : "var(--color-background-hover, rgba(82, 96, 105, 0.078))"
                    }
                },
                children: opt.label
            }, opt.key);
        })
    });
};
const UseCustomModelFooter = ({ onActivate, disabled })=>{
    const { _ } = useSafeLingui();
    return /*#__PURE__*/ jsxs(ButtonBase, {
        onClick: disabled ? void 0 : onActivate,
        disabled: disabled,
        title: disabled ? _({
            id: 'modelPicker.useCustomModel.disabledHint',
            message: 'Pass onUseCustomModel or a requestContext to the picker to wire this action.'
        }) : void 0,
        sx: {
            width: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-start',
            gap: 1.25,
            px: 2,
            py: 1.5,
            textAlign: 'left',
            color: `var(--color-primary, ${Colors.ColorBlue500})`,
            transition: 'background-color 120ms',
            '&:hover': {
                backgroundColor: disabled ? 'transparent' : "var(--color-primary-lighter, rgba(0, 103, 223, 0.06))"
            },
            '&:focus-visible': {
                outline: 'none',
                boxShadow: "inset 0 0 0 2px var(--color-primary-focused, rgba(0, 103, 223, 0.2))"
            },
            '&.Mui-disabled': {
                opacity: 0.55
            }
        },
        children: [
            /*#__PURE__*/ jsx(Box, {
                sx: {
                    flexShrink: 0,
                    width: 30,
                    height: 30,
                    borderRadius: '8px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: "var(--color-primary-lighter, rgba(0, 103, 223, 0.10))",
                    color: `var(--color-primary, ${Colors.ColorBlue500})`
                },
                children: /*#__PURE__*/ jsx(Add, {
                    sx: {
                        fontSize: 18
                    }
                })
            }),
            /*#__PURE__*/ jsxs(Box, {
                sx: {
                    display: 'flex',
                    flexDirection: 'column',
                    minWidth: 0
                },
                children: [
                    /*#__PURE__*/ jsx(Box, {
                        component: "span",
                        sx: {
                            fontSize: 13.5,
                            fontWeight: 600,
                            lineHeight: 1.3
                        },
                        children: _({
                            id: 'modelPicker.useCustomModel.title',
                            message: 'Use custom model'
                        })
                    }),
                    /*#__PURE__*/ jsx(Box, {
                        component: "span",
                        sx: {
                            fontSize: 12,
                            color: `var(--color-foreground-de-emp, ${Colors.ColorGray550})`,
                            fontWeight: 400,
                            lineHeight: 1.3
                        },
                        children: _({
                            id: 'modelPicker.useCustomModel.subtitle',
                            message: 'Bring a model from your own connection'
                        })
                    })
                ]
            })
        ]
    });
};
export { ModelPicker };
