'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Toolbar component for the template generator
 * Updated for multi-section support
 */
import { useState, useCallback, useRef, useEffect } from 'react';
import { HiPlus, HiDocumentDuplicate, HiTrash, HiEye, HiDownload, HiUpload, HiArrowLeft, HiSave, HiFolder, HiExclamationCircle, HiChevronDown, } from 'react-icons/hi';
import { LuUndo2, LuRedo2 } from 'react-icons/lu';
import { FaLayerGroup } from 'react-icons/fa';
import { useTemplateGenerator } from '../context.js';
import { DEFAULT_FIELD } from '../types.js';
import { generate_field_id, get_template_name, is_section_path, parse_path } from '../utils/template_utils.js';
import { cn } from '../../../utils/cn.js';
import { HazoAddGroupDialog } from '../../hazo_add_group_dialog/index.js';
export function Toolbar({ on_save, on_cancel, available_templates, on_load_template, readonly = false, show_import_export = false, }) {
    const { state, actions } = useTemplateGenerator();
    const [is_name_editing, set_is_name_editing] = useState(false);
    const [template_name, set_template_name] = useState(get_template_name(state.sections));
    const [is_error_dropdown_open, set_is_error_dropdown_open] = useState(false);
    const [is_add_group_dialog_open, set_is_add_group_dialog_open] = useState(false);
    const error_dropdown_ref = useRef(null);
    // Update template name when sections change
    useEffect(() => {
        set_template_name(get_template_name(state.sections));
    }, [state.sections]);
    // Close dropdown when clicking outside
    useEffect(() => {
        function handle_click_outside(event) {
            if (error_dropdown_ref.current && !error_dropdown_ref.current.contains(event.target)) {
                set_is_error_dropdown_open(false);
            }
        }
        if (is_error_dropdown_open) {
            document.addEventListener('mousedown', handle_click_outside);
            return () => document.removeEventListener('mousedown', handle_click_outside);
        }
    }, [is_error_dropdown_open]);
    // Handle clicking on an error - navigate to that field
    const handle_error_click = useCallback((error) => {
        actions.select_item(error.field_path);
        set_is_error_dropdown_open(false);
    }, [actions]);
    // Get the current section index from selected path (for adding fields/groups)
    const get_current_section_path = useCallback(() => {
        if (!state.selected_path)
            return 's0'; // Default to first section
        if (is_section_path(state.selected_path)) {
            return state.selected_path;
        }
        // Extract section from the path
        const { section_index } = parse_path(state.selected_path);
        return `s${section_index}`;
    }, [state.selected_path]);
    // Get parent path for adding fields (section or group)
    const get_parent_path_for_add = useCallback(() => {
        if (!state.selected_path)
            return 's0';
        if (is_section_path(state.selected_path)) {
            return state.selected_path;
        }
        // If selected item is a group, add to it; otherwise add to its section
        if (state.selected_item?.type === 'group') {
            return state.selected_path;
        }
        // Extract section from the path
        const { section_index } = parse_path(state.selected_path);
        return `s${section_index}`;
    }, [state.selected_path, state.selected_item]);
    // Add new field
    const handle_add_field = useCallback(() => {
        const id = generate_field_id(state.sections, 'field');
        const field = {
            ...DEFAULT_FIELD,
            id,
            label: 'New Field',
        };
        const parent_path = get_parent_path_for_add();
        actions.add_field(parent_path, field);
    }, [state.sections, get_parent_path_for_add, actions]);
    // Open add group dialog
    const handle_add_group = useCallback(() => {
        set_is_add_group_dialog_open(true);
    }, []);
    // Handle add group dialog confirm
    const handle_add_group_confirm = useCallback((group) => {
        const parent_path = get_current_section_path();
        actions.add_group_with_fields(parent_path, group.group_name, group.fields);
    }, [get_current_section_path, actions]);
    // Add new section
    const handle_add_section = useCallback(() => {
        actions.add_section();
    }, [actions]);
    // Duplicate selected
    const handle_duplicate = useCallback(() => {
        if (state.selected_path && !is_section_path(state.selected_path)) {
            actions.duplicate_field(state.selected_path);
        }
    }, [state.selected_path, actions]);
    // Delete selected
    const handle_delete = useCallback(() => {
        if (state.selected_path) {
            actions.delete_field(state.selected_path);
        }
    }, [state.selected_path, actions]);
    // Export JSON - always outputs FormSetData format
    const handle_export = useCallback(() => {
        const data = {
            sections: state.sections,
            icons_behaviour: state.icons_behaviour,
        };
        // Remove undefined icons_behaviour
        if (!data.icons_behaviour) {
            delete data.icons_behaviour;
        }
        const json = JSON.stringify(data, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const name = get_template_name(state.sections);
        a.download = `${name.toLowerCase().replace(/\s+/g, '_')}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, [state.sections, state.icons_behaviour]);
    // Import JSON - handles both single Section and FormSetData
    const handle_import = useCallback(() => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.json';
        input.onchange = async (e) => {
            const file = e.target.files?.[0];
            if (file) {
                try {
                    const text = await file.text();
                    const parsed = JSON.parse(text);
                    // The set_template action handles both formats via normalize_to_form_set_data
                    actions.set_template(parsed);
                }
                catch (error) {
                    console.error('[HazoTemplateGenerator] Failed to import JSON:', error);
                    alert('Failed to import JSON. Please check the file format.');
                }
            }
        };
        input.click();
    }, [actions]);
    // Save template name (updates first section name)
    const handle_name_save = useCallback(() => {
        if (state.sections.length > 0) {
            actions.update_section(0, { section_name: template_name });
            actions.push_history('Rename template');
        }
        set_is_name_editing(false);
    }, [template_name, state.sections.length, actions]);
    // Check if delete is disabled (can't delete last section)
    const is_delete_disabled = !state.selected_path || (is_section_path(state.selected_path) && state.sections.length <= 1);
    // Toolbar button base styles
    const button_base = 'flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors';
    const icon_button = 'p-2 rounded-md transition-colors';
    return (_jsxs("div", { className: "flex items-center gap-2 px-3 py-2 border-b bg-muted/20 overflow-x-auto", children: [on_cancel && (_jsx("button", { onClick: on_cancel, className: cn(icon_button, 'hover:bg-muted shrink-0'), title: "Back", children: _jsx(HiArrowLeft, { className: "w-5 h-5" }) })), _jsx("div", { className: "flex items-center shrink-0", children: is_name_editing ? (_jsx("input", { type: "text", value: template_name, onChange: (e) => set_template_name(e.target.value), onBlur: handle_name_save, onKeyDown: (e) => {
                        if (e.key === 'Enter')
                            handle_name_save();
                        if (e.key === 'Escape') {
                            set_template_name(get_template_name(state.sections));
                            set_is_name_editing(false);
                        }
                    }, className: "px-2 py-1 border rounded-md text-base font-semibold bg-background focus:outline-none focus:ring-2 focus:ring-primary/50 w-40", autoFocus: true })) : (_jsx("button", { onClick: () => !readonly && set_is_name_editing(true), className: cn('px-2 py-1 text-base font-semibold rounded-md truncate max-w-[150px]', !readonly && 'hover:bg-muted cursor-pointer', readonly && 'cursor-default'), title: get_template_name(state.sections), children: get_template_name(state.sections) })) }), _jsx("div", { className: "w-px h-6 bg-border shrink-0" }), !readonly && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center gap-1 shrink-0", children: [_jsxs("button", { onClick: handle_add_field, className: cn(button_base, 'bg-primary text-primary-foreground hover:bg-primary/90'), title: "Add Field (to selected section/group)", children: [_jsx(HiPlus, { className: "w-4 h-4" }), _jsx("span", { children: "Field" })] }), _jsxs("button", { onClick: handle_add_group, className: cn(button_base, 'bg-amber-500 text-white hover:bg-amber-600'), title: "Add Group (to selected section)", children: [_jsx(HiFolder, { className: "w-4 h-4" }), _jsx("span", { children: "Group" })] }), _jsxs("button", { onClick: handle_add_section, className: cn(button_base, 'bg-blue-600 text-white hover:bg-blue-700'), title: "Add Section", children: [_jsx(FaLayerGroup, { className: "w-4 h-4" }), _jsx("span", { children: "Section" })] })] }), _jsx("div", { className: "w-px h-6 bg-border shrink-0" }), _jsxs("div", { className: "flex items-center gap-0.5 shrink-0", children: [_jsx("button", { onClick: handle_duplicate, disabled: !state.selected_path || is_section_path(state.selected_path ?? ''), className: cn(icon_button, 'hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed'), title: "Duplicate (not for sections)", children: _jsx(HiDocumentDuplicate, { className: "w-5 h-5" }) }), _jsx("button", { onClick: handle_delete, disabled: is_delete_disabled, className: cn(icon_button, 'hover:bg-red-50 dark:hover:bg-red-950/30 text-destructive disabled:opacity-30 disabled:cursor-not-allowed'), title: is_section_path(state.selected_path ?? '') && state.sections.length <= 1 ? "Can't delete last section" : "Delete", children: _jsx(HiTrash, { className: "w-5 h-5" }) })] }), _jsx("div", { className: "w-px h-6 bg-border shrink-0" }), _jsxs("div", { className: "flex items-center gap-0.5 shrink-0", children: [_jsx("button", { onClick: actions.undo, disabled: !state.can_undo, className: cn(icon_button, 'hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed'), title: "Undo (Ctrl+Z)", children: _jsx(LuUndo2, { className: "w-5 h-5" }) }), _jsx("button", { onClick: actions.redo, disabled: !state.can_redo, className: cn(icon_button, 'hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed'), title: "Redo (Ctrl+Shift+Z)", children: _jsx(LuRedo2, { className: "w-5 h-5" }) })] })] })), _jsx("div", { className: "flex-1 min-w-[20px]" }), state.validation_errors.length > 0 && (_jsxs("div", { className: "relative shrink-0", ref: error_dropdown_ref, children: [_jsxs("button", { onClick: () => set_is_error_dropdown_open(!is_error_dropdown_open), className: "flex items-center gap-1.5 px-2 py-1.5 rounded-md bg-destructive text-destructive-foreground text-sm font-medium", children: [_jsx(HiExclamationCircle, { className: "w-4 h-4" }), _jsx("span", { children: state.validation_errors.length }), _jsx(HiChevronDown, { className: cn('w-4 h-4 transition-transform', is_error_dropdown_open && 'rotate-180') })] }), is_error_dropdown_open && (_jsxs("div", { className: "absolute right-0 top-full mt-1 w-72 max-h-64 overflow-auto bg-background border rounded-lg shadow-lg z-50", children: [_jsx("div", { className: "px-3 py-2 border-b bg-muted/50 text-sm font-medium text-destructive", children: "Validation Errors" }), _jsx("div", { className: "py-1", children: state.validation_errors.map((error, index) => (_jsxs("button", { onClick: () => handle_error_click(error), className: "w-full px-3 py-2 text-left hover:bg-muted transition-colors", children: [_jsx("div", { className: "text-sm font-medium", children: error.field_id || error.field_path }), _jsx("div", { className: "text-xs text-muted-foreground", children: error.message })] }, `${error.field_path}-${index}`))) })] }))] })), _jsxs("button", { onClick: () => actions.open_preview(), className: cn(button_base, 'bg-violet-600 text-white hover:bg-violet-700 shrink-0'), title: "Preview Form", children: [_jsx(HiEye, { className: "w-4 h-4" }), _jsx("span", { children: "Preview" })] }), show_import_export && (_jsxs("div", { className: "flex items-center gap-0.5 shrink-0", children: [!readonly && (_jsx("button", { onClick: handle_import, className: cn(icon_button, 'hover:bg-muted'), title: "Import JSON", children: _jsx(HiUpload, { className: "w-5 h-5" }) })), _jsx("button", { onClick: handle_export, className: cn(icon_button, 'hover:bg-muted'), title: "Export JSON (FormSetData format)", children: _jsx(HiDownload, { className: "w-5 h-5" }) })] })), on_save && !readonly && (_jsxs("button", { onClick: on_save, disabled: state.validation_errors.length > 0, className: cn(button_base, 'bg-emerald-600 text-white hover:bg-emerald-700 shrink-0', 'disabled:opacity-50 disabled:cursor-not-allowed'), title: "Save Template", children: [_jsx(HiSave, { className: "w-4 h-4" }), _jsx("span", { children: "Save" })] })), _jsx(HazoAddGroupDialog, { open: is_add_group_dialog_open, on_open_change: set_is_add_group_dialog_open, on_confirm: handle_add_group_confirm })] }));
}
//# sourceMappingURL=toolbar.js.map