/**
 * Dialog component for adding multiple fields to a form
 * Allows users to add questions, select field types, configure options, and reorder via drag-drop
 *
 * Supports up to 3 tabs:
 * - File Textbox (opt-in via enable_file_textbox_tab)
 * - Library (opt-in via enable_library, default true)
 * - Fields (standard field types, always available)
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useMemo } from 'react';
import { cn } from '../../utils/cn.js';
import { Dialog, DialogContent, DialogHeader as DefaultDialogHeader, DialogFooter as DefaultDialogFooter, DialogTitle as DefaultDialogTitle, DialogDescription as DefaultDialogDescription, } from '../shared/dialog/index.js';
import { ADD_FIELD_TYPE_META, } from './types.js';
import { QuestionInput } from './components/question_input.js';
import { PendingFieldList } from './components/pending_field_list.js';
import { LibrarySearch } from './components/library_search.js';
/**
 * Generate a unique ID for pending fields
 */
function generate_id() {
    return `pending_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
/**
 * HazoAddFieldDialog - Dialog for adding multiple fields to a form
 *
 * Opens a modal dialog that allows users to:
 * - Enter questions/labels (one at a time, press Enter to add)
 * - Drag and drop to reorder pending fields
 * - Select field type via combobox with icons
 * - Configure type-specific options in expandable accordion
 * - Remove fields before submission
 * - Submit all fields at once
 *
 * Note: Always uses the built-in Dialog and DialogContent to ensure proper
 * portal/overlay behavior. Consumer-provided dialog_components only customize
 * DialogHeader, DialogFooter, DialogTitle, and DialogDescription.
 */
export function HazoAddFieldDialog({ open, on_open_change, on_confirm, on_cancel, title = 'Add Fields', exclude_types = [], dialog_components, combobox_components, enable_library = true, library_api_base_url, library_table_name, library_scope_id, library_filter_mode = 'both', enable_file_textbox_tab = false, default_tab, file_textbox_hide_classification, file_textbox_hide_tags, }) {
    // Always use built-in Dialog and DialogContent to ensure proper portal/overlay behavior
    // Only use consumer-provided components for inner dialog elements (header, footer, title, description)
    const DialogHeader = dialog_components?.DialogHeader ?? DefaultDialogHeader;
    const DialogFooter = dialog_components?.DialogFooter ?? DefaultDialogFooter;
    const DialogTitle = dialog_components?.DialogTitle ?? DefaultDialogTitle;
    const DialogDescription = dialog_components?.DialogDescription ?? DefaultDialogDescription;
    // Pending fields state
    const [pending_fields, set_pending_fields] = useState([]);
    // Available field types for the "Fields" tab (excludes DataTable, FileTextbox, plus any in exclude_types)
    const available_types = useMemo(() => ADD_FIELD_TYPE_META.filter(meta => meta.type !== 'HazoCollabFormDataTable'
        && meta.type !== 'HazoCollabFormFileTextbox'
        && !exclude_types.includes(meta.type)), [exclude_types]);
    // Get the default field type (first available, excluding Group)
    const default_field_type = useMemo(() => {
        const first = available_types.find(t => t.type !== 'Group');
        return first?.type || 'HazoCollabFormInputbox';
    }, [available_types]);
    // Selected field type for the input (persists across adding fields)
    const [selected_field_type, set_selected_field_type] = useState(default_field_type);
    // Determine which tabs are visible
    const has_tabs = enable_library || enable_file_textbox_tab;
    // Compute the initial tab
    const compute_initial_tab = useCallback(() => {
        if (default_tab) {
            if (default_tab === 'file_textbox' && enable_file_textbox_tab)
                return 'file_textbox';
            if (default_tab === 'library' && enable_library)
                return 'library';
            return 'fields';
        }
        if (enable_file_textbox_tab)
            return 'file_textbox';
        if (enable_library)
            return 'library';
        return 'fields';
    }, [default_tab, enable_file_textbox_tab, enable_library]);
    // Tab state
    const [active_tab, set_active_tab] = useState(compute_initial_tab);
    // Reset form when dialog opens
    useEffect(() => {
        if (open) {
            set_pending_fields([]);
            set_selected_field_type(default_field_type);
            set_active_tab(compute_initial_tab());
        }
    }, [open, default_field_type, compute_initial_tab]);
    // ========================================
    // Handlers
    // ========================================
    // Add a new question to the pending list
    const handle_add_question = useCallback((label, field_type) => {
        const new_entry = {
            id: generate_id(),
            label,
            field_type,
            required: false,
            accept_public_files: 'none',
            options: ['HazoCollabFormRadio', 'HazoCollabFormCombo'].includes(field_type)
                ? [{ label: 'Option 1', value: 'option_1' }]
                : undefined,
            date_config: field_type === 'HazoCollabFormDate'
                ? { date_mode: 'single' }
                : undefined,
            file_textbox_config: field_type === 'HazoCollabFormFileTextbox'
                ? {}
                : undefined,
            is_expanded: false,
        };
        set_pending_fields(prev => [...prev, new_entry]);
    }, []);
    // Add a file textbox field (from the File Textbox tab — type is pre-set)
    const handle_add_file_textbox = useCallback((label, _field_type) => {
        const new_entry = {
            id: generate_id(),
            label,
            field_type: 'HazoCollabFormFileTextbox',
            required: false,
            accept_public_files: 'none',
            file_textbox_config: {},
            is_expanded: false,
        };
        set_pending_fields(prev => [...prev, new_entry]);
    }, []);
    // Handle selection from library search
    const handle_library_select = useCallback((entry) => {
        set_pending_fields(prev => [...prev, entry]);
    }, []);
    // Change field type
    const handle_type_change = useCallback((id, type) => {
        set_pending_fields(prev => prev.map(field => field.id === id
            ? {
                ...field,
                field_type: type,
                // Reset type-specific options when type changes
                options: ['HazoCollabFormRadio', 'HazoCollabFormCombo'].includes(type)
                    ? field.options || [{ label: 'Option 1', value: 'option_1' }]
                    : undefined,
                date_config: type === 'HazoCollabFormDate'
                    ? field.date_config || { date_mode: 'single' }
                    : undefined,
                checkbox_config: type === 'HazoCollabFormCheckbox'
                    ? field.checkbox_config
                    : undefined,
                file_textbox_config: type === 'HazoCollabFormFileTextbox'
                    ? field.file_textbox_config || {}
                    : undefined,
                // Reset accept_public_files for Document type and File Textbox
                accept_public_files: (type === 'HazoCollabFormDoc' || type === 'HazoCollabFormFileTextbox') ? 'none' : field.accept_public_files,
            }
            : field));
    }, []);
    // Remove a field
    const handle_remove = useCallback((id) => {
        set_pending_fields(prev => prev.filter(field => field.id !== id));
    }, []);
    // Reorder after drag-drop
    const handle_reorder = useCallback((items) => {
        set_pending_fields(items);
    }, []);
    // Toggle accordion expand
    const handle_toggle_expand = useCallback((id) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, is_expanded: !field.is_expanded } : field));
    }, []);
    // Toggle required
    const handle_required_change = useCallback((id, value) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, required: value } : field));
    }, []);
    // Change accept_public_files mode
    const handle_accept_files_change = useCallback((id, value) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, accept_public_files: value } : field));
    }, []);
    // Update options (Radio/Combo)
    const handle_options_change = useCallback((id, options) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, options } : field));
    }, []);
    // Update date config
    const handle_date_config_change = useCallback((id, config) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, date_config: config } : field));
    }, []);
    // Update checkbox config
    const handle_checkbox_config_change = useCallback((id, config) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, checkbox_config: config } : field));
    }, []);
    // Update file textbox config
    const handle_file_textbox_config_change = useCallback((id, config) => {
        set_pending_fields(prev => prev.map(field => field.id === id ? { ...field, file_textbox_config: config } : field));
    }, []);
    // Convert pending fields to NewFieldDefinition[] and submit
    const handle_confirm = useCallback(() => {
        if (pending_fields.length === 0)
            return;
        const new_fields = pending_fields.map(field => {
            const definition = {
                field_type: field.field_type,
                label: field.label,
                required: field.required,
            };
            // Add type-specific options
            if (['HazoCollabFormRadio', 'HazoCollabFormCombo'].includes(field.field_type) && field.options) {
                definition.options = field.options;
            }
            if (field.field_type === 'HazoCollabFormDate' && field.date_config) {
                definition.date_config = field.date_config;
            }
            if (field.field_type === 'HazoCollabFormCheckbox' && field.checkbox_config) {
                definition.checkbox_config = field.checkbox_config;
            }
            if (field.field_type === 'HazoCollabFormFileTextbox' && field.file_textbox_config) {
                definition.file_textbox_config = field.file_textbox_config;
            }
            if (field.accept_public_files && field.accept_public_files !== 'none' && field.field_type !== 'HazoCollabFormDoc' && field.field_type !== 'Group' && field.field_type !== 'HazoCollabFormFileTextbox') {
                definition.accept_public_files = field.accept_public_files;
            }
            // Pass through library source config for full FieldConfig preservation
            if (field.source === 'library' && field.source_config) {
                definition.source_config = field.source_config;
            }
            return definition;
        });
        on_confirm(new_fields);
        on_open_change(false);
    }, [pending_fields, on_confirm, on_open_change]);
    // Handle cancel
    const handle_cancel = useCallback(() => {
        on_cancel?.();
        on_open_change(false);
    }, [on_cancel, on_open_change]);
    // Determine button text
    const field_count = pending_fields.length;
    const has_group = pending_fields.some(f => f.field_type === 'Group');
    const button_text = field_count === 0
        ? 'Add Fields'
        : field_count === 1
            ? (has_group ? 'Add Group' : 'Add Field')
            : `Add ${field_count} Fields`;
    // File Textbox tab uses a locked type — only show label input, no type selector
    const file_textbox_type_meta = useMemo(() => ADD_FIELD_TYPE_META.filter(m => m.type === 'HazoCollabFormFileTextbox'), []);
    // Tab button helper
    const tab_button = (tab, label) => (_jsx("button", { type: "button", onClick: () => set_active_tab(tab), className: cn('cls_add_field_tab px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px', active_tab === tab
            ? 'border-primary text-primary'
            : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/50'), children: label }, tab));
    return (_jsx(Dialog, { open: open, onOpenChange: on_open_change, children: _jsxs(DialogContent, { className: "cls_add_field_dialog_content", style: { maxWidth: '800px' }, prevent_close_on_outside_click: true, children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: title }), _jsx(DialogDescription, { children: "Add multiple fields to your form." })] }), _jsxs("div", { className: "space-y-4 py-2", children: [has_tabs && (_jsxs("div", { className: "flex border-b", children: [enable_file_textbox_tab && tab_button('file_textbox', 'File Textbox'), enable_library && tab_button('library', 'Library'), tab_button('fields', 'Fields')] })), active_tab === 'file_textbox' && enable_file_textbox_tab && (_jsx(QuestionInput, { on_add: handle_add_file_textbox, auto_focus: true, available_types: file_textbox_type_meta, selected_type: 'HazoCollabFormFileTextbox', on_type_change: () => { }, combobox_components: combobox_components, hide_type_selector: true, placeholder: "Enter a label for the file textbox field..." })), active_tab === 'library' && enable_library && (_jsx(LibrarySearch, { api_base_url: library_api_base_url, table_name: library_table_name, scope_id: library_scope_id, filter_mode: library_filter_mode, on_select: handle_library_select })), active_tab === 'fields' && (_jsx(QuestionInput, { on_add: handle_add_question, auto_focus: !has_tabs, available_types: available_types, selected_type: selected_field_type, on_type_change: set_selected_field_type, combobox_components: combobox_components })), _jsx(PendingFieldList, { items: pending_fields, available_types: available_types, on_reorder: handle_reorder, on_type_change: handle_type_change, on_remove: handle_remove, on_toggle_expand: handle_toggle_expand, on_required_change: handle_required_change, on_accept_files_change: handle_accept_files_change, on_options_change: handle_options_change, on_date_config_change: handle_date_config_change, on_checkbox_config_change: handle_checkbox_config_change, on_file_textbox_config_change: handle_file_textbox_config_change, combobox_components: combobox_components, file_textbox_hide_classification: file_textbox_hide_classification, file_textbox_hide_tags: file_textbox_hide_tags })] }), _jsxs(DialogFooter, { className: "flex-row gap-3", children: [_jsx("button", { type: "button", onClick: handle_confirm, disabled: field_count === 0, className: cn('cls_add_field_dialog_confirm inline-flex h-10 items-center justify-center rounded-md px-4 py-2 text-sm font-medium ring-offset-background transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', field_count > 0
                                ? 'bg-primary text-primary-foreground hover:bg-primary/90'
                                : 'bg-muted text-muted-foreground cursor-not-allowed'), children: button_text }), _jsx("button", { type: "button", onClick: handle_cancel, className: "cls_add_field_dialog_cancel inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", children: "Cancel" })] })] }) }));
}
//# sourceMappingURL=hazo_add_field_dialog.js.map