'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * TemplateLoaderDialog - Dialog with template dropdown to populate library
 */
import { useState, useCallback } from 'react';
import { HiDocument, HiFolder } from 'react-icons/hi';
import { HazoUiDialog } from 'hazo_ui';
import { useFieldLibrary } from '../context.js';
import { template_to_elements } from '../utils/template_to_elements.js';
import { format_full_key } from '../utils/key_utils.js';
function ElementIcon({ type }) {
    if (type === 'group') {
        return _jsx(HiFolder, { className: "h-3.5 w-3.5 flex-shrink-0 text-amber-500" });
    }
    return _jsx(HiDocument, { className: "h-3.5 w-3.5 flex-shrink-0 text-blue-500" });
}
export function TemplateLoaderDialog({ open, on_close, templates, }) {
    const { elements: { elements, create_element, fetch_elements }, } = useFieldLibrary();
    const [selected_index, set_selected_index] = useState(-1);
    const [is_loading, set_is_loading] = useState(false);
    const [result, set_result] = useState(null);
    const [error, set_error] = useState(null);
    const handle_load = useCallback(async () => {
        if (selected_index < 0 || selected_index >= templates.length)
            return;
        const template = templates[selected_index];
        set_is_loading(true);
        set_result(null);
        set_error(null);
        try {
            // Get sections
            let sections;
            if (template.sections) {
                sections = template.sections;
            }
            else if (template.load) {
                sections = await template.load();
            }
            else {
                set_error('Template has no data');
                set_is_loading(false);
                return;
            }
            // Convert to elements
            const converted = template_to_elements(sections);
            // Build existing key set
            const existing_keys = new Set(elements.map(e => format_full_key(e.area, e.key)));
            // Insert non-duplicates
            let loaded = 0;
            let skipped = 0;
            const loaded_entries = [];
            const skipped_entries = [];
            for (const el of converted) {
                const full_key = format_full_key(el.area, el.key);
                const el_type = el.element.field_type === 'group' ? 'group' : 'field';
                if (existing_keys.has(full_key)) {
                    skipped++;
                    skipped_entries.push({ key: full_key, type: el_type });
                    continue;
                }
                const created = await create_element(el.area, el.key, JSON.stringify(el.element));
                if (created) {
                    existing_keys.add(full_key);
                    loaded++;
                    loaded_entries.push({ key: full_key, type: el_type });
                }
            }
            set_result({ loaded, skipped, total: converted.length, loaded_entries, skipped_entries });
            // Refresh the library list
            if (loaded > 0) {
                await fetch_elements();
            }
        }
        catch (err) {
            set_error(err instanceof Error ? err.message : 'Failed to load template');
        }
        finally {
            set_is_loading(false);
        }
    }, [selected_index, templates, elements, create_element, fetch_elements]);
    const handle_close = useCallback(() => {
        set_selected_index(-1);
        set_result(null);
        set_error(null);
        on_close();
    }, [on_close]);
    return (_jsx(HazoUiDialog, { open: open, onOpenChange: (v) => { if (!v)
            handle_close(); }, title: "Import from Template", description: "Load fields and groups from a form template into the library. Duplicate elements are automatically skipped.", sizeWidth: "28rem", actionButtonText: is_loading ? 'Loading...' : 'Load', actionButtonLoading: is_loading, actionButtonDisabled: selected_index < 0 || is_loading, onConfirm: handle_load, cancelButtonText: "Close", onCancel: handle_close, children: _jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("label", { className: "text-sm font-medium", children: "Template" }), _jsxs("select", { className: "h-9 px-3 text-sm border rounded-md bg-background w-full", value: selected_index, onChange: (e) => {
                                set_selected_index(Number(e.target.value));
                                set_result(null);
                                set_error(null);
                            }, disabled: is_loading, children: [_jsx("option", { value: -1, children: "Select a template..." }), templates.map((t, i) => (_jsx("option", { value: i, children: t.label }, i)))] })] }), result && (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsxs("div", { className: "text-sm px-3 py-2 rounded-md bg-muted", children: [result.loaded > 0 ? (_jsxs("span", { className: "text-green-700 dark:text-green-400", children: ["Loaded ", result.loaded, " element", result.loaded !== 1 ? 's' : ''] })) : (_jsx("span", { className: "text-muted-foreground", children: "No new elements to load" })), result.skipped > 0 && (_jsxs("span", { className: "text-muted-foreground", children: [' ', "(", result.skipped, " already in library)"] }))] }), _jsxs("div", { className: "max-h-48 overflow-y-auto border rounded-md text-xs", children: [result.loaded_entries.length > 0 && (_jsxs("div", { className: "px-3 py-2", children: [_jsxs("div", { className: "font-medium text-green-700 dark:text-green-400 mb-1", children: ["Loaded (", result.loaded_entries.length, ")"] }), _jsx("ul", { className: "space-y-0.5", children: result.loaded_entries.map(e => (_jsxs("li", { className: "flex items-center gap-1.5 text-muted-foreground", children: [_jsx(ElementIcon, { type: e.type }), _jsx("span", { className: "font-mono", children: e.key })] }, e.key))) })] })), result.skipped_entries.length > 0 && (_jsxs("div", { className: `px-3 py-2 ${result.loaded_entries.length > 0 ? 'border-t' : ''}`, children: [_jsxs("div", { className: "font-medium text-muted-foreground mb-1", children: ["Skipped (", result.skipped_entries.length, ")"] }), _jsx("ul", { className: "space-y-0.5", children: result.skipped_entries.map(e => (_jsxs("li", { className: "flex items-center gap-1.5 text-muted-foreground/70", children: [_jsx(ElementIcon, { type: e.type }), _jsx("span", { className: "font-mono", children: e.key })] }, e.key))) })] }))] })] })), error && (_jsx("div", { className: "text-sm px-3 py-2 rounded-md bg-destructive/10 text-destructive", children: error }))] }) }));
}
//# sourceMappingURL=template_loader_dialog.js.map