import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState, } from "react";
import { AlertCircle, ExternalLink, RefreshCw } from "lucide-react";
import { Button } from "../../../components/ui/button";
import { CloseButton } from "../../../components/ui/close-button";
import { FieldListFieldWithFallbacks } from "../../FieldListFieldWithFallbacks";
import { useEditContext } from "../../client/editContext";
export function findFieldInItem(item, aliases) {
    return item.fields.find((field) => {
        const candidates = [field.name, field.displayName].filter(Boolean);
        return candidates.some((candidate) => aliases.includes(candidate));
    });
}
async function loadItem(editContext, descriptor) {
    if (!editContext)
        return undefined;
    return editContext.itemsRepository.getItem(descriptor);
}
export function GroupedFieldConfigPanel({ itemId, title, onClose, actions, supplementalContent, refreshToken = 0, fieldGroups, headerIcon, headerSubline, loadErrorTitle = "Unable to load item", emptyMessage = "No editable settings were found for this item.", fallbackTitle = "Configuration", footerHint, footerLeadingText = "For advanced options and all fields use the ", showFullEditorButton = true, }) {
    const editContext = useEditContext();
    const editContextRef = useRef(editContext);
    editContextRef.current = editContext;
    const [item, setItem] = useState();
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const itemDescriptor = useMemo(() => ({
        id: itemId,
        language: "en",
        version: 0,
    }), [itemId]);
    const refreshItem = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            const loadedItem = await loadItem(editContextRef.current, itemDescriptor);
            if (!loadedItem) {
                setItem(undefined);
                setError("Item could not be loaded.");
                return;
            }
            setItem(loadedItem);
        }
        catch (e) {
            setItem(undefined);
            setError(e instanceof Error ? e.message : "Failed to load item.");
        }
        finally {
            setLoading(false);
        }
    }, [itemDescriptor]);
    useEffect(() => {
        void refreshItem();
    }, [refreshItem, refreshToken]);
    const resolvedGroups = useMemo(() => {
        if (!item)
            return [];
        return fieldGroups
            .map((group) => ({
            title: group.title,
            description: group.description,
            icon: group.icon,
            fields: group.fieldNames
                .map((aliases) => findFieldInItem(item, aliases))
                .filter((field) => Boolean(field)),
        }))
            .filter((group) => group.fields.length > 0);
    }, [item, fieldGroups]);
    const handleOpenFullEditor = useCallback(async () => {
        const ctx = editContextRef.current;
        if (!ctx || !item)
            return;
        await ctx.loadItem(item.descriptor, { addToBrowseHistory: false });
        ctx.switchWorkspace("editor");
    }, [item]);
    const defaultFooter = (_jsxs("p", { className: "text-neutral-grey-50 pb-2 text-center text-[11px]", children: [footerLeadingText, _jsx("button", { type: "button", className: "text-neutral-grey-50 decoration-border-default hover:text-neutral-grey-100 underline underline-offset-2", onClick: handleOpenFullEditor, disabled: !item, children: "full editor" }), "."] }));
    return (_jsxs("div", { className: "bg-neutral-grey-5/60 flex h-full flex-col", children: [_jsxs("div", { className: "border-border-default flex items-center justify-between gap-3 border-b bg-white px-5 py-3.5", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-3", children: [_jsx("div", { className: "bg-highlight-10 text-highlight-100 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg", children: headerIcon }), _jsxs("div", { className: "min-w-0", children: [_jsx("h2", { className: "text-neutral-grey-100 truncate text-sm font-semibold", children: title || item?.name || fallbackTitle }), headerSubline && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 flex min-w-0 items-center gap-1 text-[11px]", children: headerSubline }))] })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-1.5", children: [actions, showFullEditorButton && (_jsxs(Button, { variant: "outline", size: "sm", onClick: handleOpenFullEditor, disabled: !item, children: [_jsx(ExternalLink, { className: "h-3.5 w-3.5", strokeWidth: 1.5 }), "Full Editor"] })), onClose && (_jsx(CloseButton, { onClick: onClose, label: "Close configuration panel" }))] })] }), _jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: loading ? (_jsxs("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center text-sm", children: [_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin", strokeWidth: 1.5 }), "Loading..."] })) : error ? (_jsxs("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red m-5 rounded-lg border p-4 text-sm", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(AlertCircle, { className: "h-4 w-4", strokeWidth: 1.5 }), loadErrorTitle] }), _jsx("p", { className: "mt-2 whitespace-pre-wrap", children: error })] })) : !resolvedGroups.length ? (_jsxs("div", { className: "space-y-4 p-5", children: [supplementalContent, _jsx("div", { className: "border-border-default text-neutral-grey-50 rounded-lg border bg-white p-4 text-sm", children: emptyMessage })] })) : (_jsxs("div", { className: "space-y-4 p-5", children: [supplementalContent, (() => {
                            let nextTab = 1;
                            return resolvedGroups.map((group) => {
                                const tabStart = nextTab;
                                nextTab += group.fields.length;
                                return (_jsxs("div", { className: "border-border-default overflow-hidden rounded-lg border bg-white", children: [_jsxs("div", { className: "border-border-default flex items-center gap-2.5 border-b px-4 py-3", children: [_jsx("span", { className: "bg-neutral-grey-5 text-neutral-grey-50 flex h-6 w-6 items-center justify-center rounded-md", children: group.icon }), _jsxs("div", { children: [_jsx("h3", { className: "text-neutral-grey-100 text-xs font-semibold tracking-wide", children: group.title }), _jsx("p", { className: "text-neutral-grey-50 text-[11px] leading-tight", children: group.description })] })] }), _jsx("div", { className: "divide-border-default badge-pad divide-y", children: group.fields.map((field, index) => (_jsx("div", { className: "py-1", children: _jsx(FieldListFieldWithFallbacks, { fieldDescriptor: field.descriptor, validators: [], simplified: true, tabIndex: tabStart + index }) }, field.id))) })] }, group.title));
                            });
                        })(), footerHint ?? defaultFooter] })) })] }));
}
export default GroupedFieldConfigPanel;
//# sourceMappingURL=GroupedFieldConfigPanel.js.map