'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Element editor - Right panel: editor wrapper with tabs + save/delete
 */
import { useState, useCallback, useMemo, useEffect } from 'react';
import { HiSave, HiTrash, HiPlus, HiUpload, HiDownload } from 'react-icons/hi';
import { useFieldLibrary } from '../context.js';
import { parse_element, stringify_element, is_field_element, is_group_element, create_default_field, create_default_group } from '../utils/element_utils.js';
import { label_to_key, format_full_key } from '../utils/key_utils.js';
import { AreaCombobox } from './area_combobox.js';
import { ReferencePicker } from './reference_picker.js';
import { RawJsonViewer } from './raw_json_viewer.js';
import { ImportExportDialog } from './import_export_dialog.js';
import { BasicTab } from '../../hazo_template_generator/components/tabs/basic_tab.js';
import { TypeTab } from '../../hazo_template_generator/components/tabs/type_tab.js';
import { ValidationTab } from '../../hazo_template_generator/components/tabs/validation_tab.js';
import { ControlsTab } from '../../hazo_template_generator/components/tabs/controls_tab.js';
import { cn } from '../../../utils/cn.js';
import { EditorSection, EditorLabel, EditorInput, EditorTextArea, EditorHeader, EditorTabs, StatusIndicator, LABEL_ICONS, } from '../../shared/editor_theme/index.js';
export function ElementEditor() {
    const { selected_id, set_selected_id, set_active_tab, active_tab: library_tab, area_filter, elements: { elements, areas, update_element, delete_element, create_element }, } = useFieldLibrary();
    const [editor_tab, set_editor_tab] = useState('basic');
    const [local_area, set_local_area] = useState('');
    const [local_key, set_local_key] = useState('');
    const [local_data, set_local_data] = useState(null);
    const [is_dirty, set_is_dirty] = useState(false);
    const [saving, set_saving] = useState(false);
    // Find the selected record
    const selected_record = useMemo(() => {
        if (!selected_id)
            return null;
        return elements.find(e => e.id === selected_id) ?? null;
    }, [elements, selected_id]);
    // Check if this is a new (unsaved) element - supports __new_field_ and __new_group_ prefixes
    const is_new = selected_id?.startsWith('__new_') ?? false;
    const new_type = selected_id?.startsWith('__new_field_')
        ? 'field'
        : selected_id?.startsWith('__new_group_')
            ? 'group'
            : selected_id?.startsWith('__new_')
                ? (library_tab === 'groups' ? 'group' : 'field')
                : null;
    // Load selected record into local state, or create defaults for new elements
    useEffect(() => {
        if (selected_record) {
            set_local_area(selected_record.area);
            set_local_key(selected_record.key);
            const data = parse_element(selected_record.element);
            set_local_data(data);
            set_is_dirty(false);
            set_editor_tab('basic');
        }
        else if (is_new) {
            // New element: initialize with defaults
            const default_area = area_filter || '';
            set_local_area(default_area);
            set_local_key('');
            if (new_type === 'group') {
                set_local_data(create_default_group('', 'New Group'));
            }
            else {
                set_local_data(create_default_field('', 'New Field'));
            }
            set_is_dirty(true);
            set_editor_tab('basic');
        }
        else {
            set_local_data(null);
            set_is_dirty(false);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selected_record, selected_id]);
    // Handle field data updates (from tab editors)
    const handle_field_update = useCallback((updates) => {
        if (!local_data)
            return;
        set_local_data(prev => {
            if (!prev)
                return prev;
            return { ...prev, ...updates };
        });
        set_is_dirty(true);
        // Auto-generate key from label if key is empty
        if (updates.label && !local_key) {
            set_local_key(label_to_key(updates.label));
        }
    }, [local_data, local_key]);
    // Handle group reference updates
    const handle_references_change = useCallback((references) => {
        if (!local_data || !is_group_element(local_data))
            return;
        set_local_data(prev => {
            if (!prev || !is_group_element(prev))
                return prev;
            return { ...prev, reference_element: references };
        });
        set_is_dirty(true);
    }, [local_data]);
    // Navigate to a referenced field
    const handle_navigate_to_field = useCallback((full_key) => {
        // full_key format: "area.key"
        const dot_idx = full_key.indexOf('.');
        if (dot_idx < 0)
            return;
        const area = full_key.slice(0, dot_idx);
        const key = full_key.slice(dot_idx + 1);
        const record = elements.find(e => e.area === area && e.key === key);
        if (record) {
            set_active_tab('fields');
            set_selected_id(record.id);
        }
    }, [elements, set_active_tab, set_selected_id]);
    // No-op commit (tabs call on_commit for history in template generator; not needed here)
    const handle_commit = useCallback(() => { }, []);
    // Save element
    const handle_save = useCallback(async () => {
        if (!local_data || !local_area || !local_key)
            return;
        set_saving(true);
        try {
            // Ensure id matches key
            const save_data = { ...local_data, id: local_key };
            const element_json = stringify_element(save_data);
            if (is_new) {
                const created = await create_element(local_area, local_key, element_json);
                if (created) {
                    set_selected_id(created.id);
                    set_is_dirty(false);
                }
            }
            else if (selected_record) {
                const updated = await update_element(selected_record.id, {
                    area: local_area,
                    key: local_key,
                    element: element_json,
                });
                if (updated) {
                    set_is_dirty(false);
                }
            }
        }
        finally {
            set_saving(false);
        }
    }, [local_data, local_area, local_key, is_new, selected_record, create_element, update_element, set_selected_id]);
    // Delete element
    const handle_delete = useCallback(async () => {
        if (is_new) {
            set_selected_id(null);
            return;
        }
        if (!selected_record)
            return;
        const ok = await delete_element(selected_record.id);
        if (ok) {
            set_selected_id(null);
        }
    }, [is_new, selected_record, delete_element, set_selected_id]);
    // No element selected - show action buttons
    if (!selected_id || !local_data) {
        return _jsx(EmptyState, {});
    }
    const is_field = is_field_element(local_data);
    const is_group = is_group_element(local_data);
    // Tabs to show: fields get all tabs, groups get basic + controls
    const tabs = is_field
        ? [
            { id: 'basic', label: 'Basic', icon: 'basic' },
            { id: 'type', label: 'Type', icon: 'type' },
            { id: 'validation', label: 'Validation', icon: 'validation' },
            { id: 'controls', label: 'Controls', icon: 'controls' },
        ]
        : [
            { id: 'basic', label: 'Basic', icon: 'basic' },
            { id: 'controls', label: 'Controls', icon: 'controls' },
        ];
    // Build raw JSON for viewer
    const full_record_preview = {
        area: local_area,
        key: local_key,
        full_key: format_full_key(local_area, local_key),
        element: local_data,
    };
    const can_save = !saving && local_area && local_key && is_dirty;
    return (_jsxs("div", { className: "flex flex-col h-full", children: [_jsxs(EditorHeader, { children: [_jsxs("div", { className: "flex items-end gap-3", children: [_jsxs("div", { className: "flex-1 grid grid-cols-2 gap-3", children: [_jsxs("div", { className: "space-y-1", children: [_jsx(EditorLabel, { icon: LABEL_ICONS.area, children: "Area" }), _jsx(AreaCombobox, { value: local_area, on_change: (area) => { set_local_area(area); set_is_dirty(true); }, areas: areas, placeholder: "Select area..." })] }), _jsxs("div", { className: "space-y-1", children: [_jsx(EditorLabel, { icon: LABEL_ICONS.id, children: "Key" }), _jsx(EditorInput, { type: "text", value: local_key, onChange: (e) => {
                                                    set_local_key(e.target.value.toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_+\-#]/g, ''));
                                                    set_is_dirty(true);
                                                }, field_width: "full", className: "font-mono", placeholder: "element_key" })] })] }), _jsxs("button", { type: "button", onClick: handle_save, disabled: !can_save, className: cn('flex items-center gap-1.5 px-4 py-2 text-sm text-primary-foreground bg-primary rounded-md hover:bg-primary/90 transition-colors shrink-0', !can_save && 'opacity-50 cursor-not-allowed'), children: [_jsx(HiSave, { className: "h-4 w-4" }), saving ? 'Saving...' : 'Save'] })] }), local_area && local_key && (_jsxs("div", { className: "text-xs text-muted-foreground mt-2", children: ["Full key: ", _jsx("span", { className: "font-mono font-medium", children: format_full_key(local_area, local_key) })] }))] }), _jsx(EditorTabs, { tabs: tabs, active_tab: editor_tab, on_tab_change: (tab) => set_editor_tab(tab) }), _jsxs("div", { className: "flex-1 overflow-auto p-4", children: [is_field && editor_tab === 'basic' && (_jsx(BasicTab, { field: local_data, on_update: handle_field_update, on_commit: handle_commit })), is_field && editor_tab === 'type' && (_jsx(TypeTab, { field: local_data, on_update: handle_field_update, on_commit: handle_commit })), is_field && editor_tab === 'validation' && (_jsx(ValidationTab, { field: local_data, on_update: handle_field_update, on_commit: handle_commit })), is_field && editor_tab === 'controls' && (_jsx(ControlsTab, { field: local_data, is_group: false, on_update: handle_field_update, on_commit: handle_commit })), is_group && editor_tab === 'basic' && (_jsxs("div", { children: [_jsxs(EditorSection, { children: [_jsx(EditorLabel, { icon: LABEL_ICONS.label, required: true, children: "Label" }), _jsx(EditorInput, { type: "text", value: local_data.label || '', onChange: (e) => {
                                            set_local_data(prev => prev ? { ...prev, label: e.target.value } : prev);
                                            set_is_dirty(true);
                                            if (!local_key) {
                                                set_local_key(label_to_key(e.target.value));
                                            }
                                        }, placeholder: "Group label" })] }), _jsxs(EditorSection, { children: [_jsx(EditorLabel, { icon: LABEL_ICONS.description, children: "Description" }), _jsx(EditorTextArea, { value: local_data.description || '', onChange: (e) => {
                                            set_local_data(prev => prev ? { ...prev, description: e.target.value } : prev);
                                            set_is_dirty(true);
                                        }, rows: 3, placeholder: "Group description" })] }), _jsx(EditorSection, { last: true, children: _jsx(ReferencePicker, { references: local_data.reference_element || [], on_change: handle_references_change, all_elements: elements, on_navigate_to_field: handle_navigate_to_field }) })] })), is_group && editor_tab === 'controls' && (_jsx(ControlsTab, { field: { ...local_data, value: '' }, is_group: true, on_update: handle_field_update, on_commit: handle_commit })), _jsx("div", { className: "mt-6", children: _jsx(RawJsonViewer, { data: full_record_preview, label: "Raw JSON" }) })] }), _jsxs("div", { className: "p-3 border-t flex items-center justify-between", children: [_jsxs("button", { type: "button", onClick: handle_delete, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm text-destructive border border-destructive/30 rounded-md hover:bg-destructive/10 transition-colors", children: [_jsx(HiTrash, { className: "h-4 w-4" }), "Delete"] }), _jsx(StatusIndicator, { saved: !is_dirty })] })] }));
}
/**
 * Empty state shown when no element is selected - includes Import/Export/Add buttons
 */
function EmptyState() {
    const { set_selected_id, set_active_tab, } = useFieldLibrary();
    const [import_export_open, set_import_export_open] = useState(false);
    const [import_export_mode, set_import_export_mode] = useState('import');
    const handle_add_group = useCallback(() => {
        set_active_tab('groups');
        const temp_id = `__new_group_${Date.now()}`;
        set_selected_id(temp_id);
    }, [set_selected_id, set_active_tab]);
    const handle_add_field = useCallback(() => {
        set_active_tab('fields');
        const temp_id = `__new_field_${Date.now()}`;
        set_selected_id(temp_id);
    }, [set_selected_id, set_active_tab]);
    const handle_open_import = useCallback(() => {
        set_import_export_mode('import');
        set_import_export_open(true);
    }, []);
    const handle_open_export = useCallback(() => {
        set_import_export_mode('export');
        set_import_export_open(true);
    }, []);
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: "flex items-center justify-center h-full text-muted-foreground", children: _jsxs("div", { className: "text-center space-y-4", children: [_jsxs("div", { className: "flex items-center justify-center gap-2", children: [_jsxs("button", { onClick: handle_open_import, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm border rounded-md hover:bg-muted transition-colors text-muted-foreground", title: "Import elements from JSON", children: [_jsx(HiUpload, { className: "h-4 w-4" }), "Import"] }), _jsxs("button", { onClick: handle_open_export, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm border rounded-md hover:bg-muted transition-colors text-muted-foreground", title: "Export elements to JSON", children: [_jsx(HiDownload, { className: "h-4 w-4" }), "Export"] }), _jsxs("button", { onClick: handle_add_group, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm text-primary-foreground bg-primary rounded-md hover:bg-primary/90 transition-colors", children: [_jsx(HiPlus, { className: "h-4 w-4" }), "Add Group"] }), _jsxs("button", { onClick: handle_add_field, className: "flex items-center gap-1.5 px-3 py-1.5 text-sm border border-primary text-primary rounded-md hover:bg-primary/10 transition-colors", children: [_jsx(HiPlus, { className: "h-4 w-4" }), "Add Field"] })] }), _jsxs("div", { children: [_jsx("p", { className: "text-sm", children: "Select an element to edit" }), _jsx("p", { className: "text-xs mt-1", children: "or create a new one" })] })] }) }), _jsx(ImportExportDialog, { open: import_export_open, on_close: () => set_import_export_open(false), initial_mode: import_export_mode })] }));
}
//# sourceMappingURL=element_editor.js.map