import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AlertCircle, ExternalLink, RefreshCw, X } from "lucide-react";
import { Button } from "../../../components/ui/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: editContext?.item?.language ??
            editContext?.currentItemDescriptor?.language ??
            "en",
        version: 0,
    }), [
        editContext?.currentItemDescriptor?.language,
        editContext?.item?.language,
        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: "pb-2 text-center text-[11px] text-gray-400", children: [footerLeadingText, _jsx("button", { type: "button", className: "text-gray-500 underline decoration-gray-300 underline-offset-2 hover:text-gray-700", onClick: handleOpenFullEditor, disabled: !item, children: "full editor" }), "."] }));
    return (_jsxs("div", { className: "flex h-full flex-col bg-gray-50/60", children: [_jsxs("div", { className: "flex items-center justify-between gap-3 border-b border-gray-200 bg-white px-5 py-3.5", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-3", children: [_jsx("div", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gray-900 text-white", children: headerIcon }), _jsxs("div", { className: "min-w-0", children: [_jsx("h2", { className: "truncate text-sm font-semibold text-gray-900", children: title || item?.name || fallbackTitle }), headerSubline && (_jsx("div", { className: "mt-0.5 flex min-w-0 items-center gap-1 text-[11px] text-gray-400", 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(Button, { variant: "ghost", size: "icon", onClick: onClose, children: _jsx(X, { className: "h-4 w-4", strokeWidth: 1.5 }) }))] })] }), _jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: loading ? (_jsxs("div", { className: "flex h-full items-center justify-center text-sm text-gray-500", children: [_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin", strokeWidth: 1.5 }), "Loading..."] })) : error ? (_jsxs("div", { className: "m-5 rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700", 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: "rounded-lg border border-gray-200 bg-white p-4 text-sm text-gray-600", 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: "overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm", children: [_jsxs("div", { className: "flex items-center gap-2.5 border-b border-gray-100 px-4 py-3", children: [_jsx("span", { className: "flex h-6 w-6 items-center justify-center rounded-md bg-gray-100 text-gray-500", children: group.icon }), _jsxs("div", { children: [_jsx("h3", { className: "text-xs font-semibold tracking-wide text-gray-800", children: group.title }), _jsx("p", { className: "text-[11px] leading-tight text-gray-400", children: group.description })] })] }), _jsx("div", { className: "divide-y divide-gray-50 px-2 py-1", 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