/**
 * Dialog component for adding a new group with optional fields
 * Similar to HazoAddFieldDialog but starts with a group name input
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useMemo, useRef } 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 '../hazo_add_field_dialog/types.js';
import { QuestionInput } from '../hazo_add_field_dialog/components/question_input.js';
import { PendingFieldList } from '../hazo_add_field_dialog/components/pending_field_list.js';
import { LibrarySearch } from '../hazo_add_field_dialog/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)}`;
}
/**
 * HazoAddGroupDialog - Dialog for adding a new group with optional fields
 *
 * Opens a modal dialog that allows users to:
 * - Enter a group name (required)
 * - Optionally add fields to the group
 * - Drag and drop to reorder pending fields
 * - Configure field-specific options
 * - Submit the group with all fields
 *
 * 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 HazoAddGroupDialog({ open, on_open_change, on_confirm, on_cancel, title = 'Add Group', default_group_name = '', exclude_types = [], dialog_components, combobox_components, enable_library = true, library_api_base_url, library_table_name, library_scope_id, }) {
    // 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;
    // Group name state
    const [group_name, set_group_name] = useState(default_group_name);
    const group_name_input_ref = useRef(null);
    // Pending fields state
    const [pending_fields, set_pending_fields] = useState([]);
    // Available field types - always exclude Group (no nesting) and DataTable
    const available_types = useMemo(() => ADD_FIELD_TYPE_META.filter(meta => meta.type !== 'HazoCollabFormDataTable' &&
        meta.type !== 'Group' &&
        !exclude_types.includes(meta.type)), [exclude_types]);
    // Get the default field type (first available)
    const default_field_type = useMemo(() => {
        const first = available_types[0];
        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);
    // Tab state for library/custom toggle (only used when enable_library is true)
    const [active_tab, set_active_tab] = useState(enable_library ? 'library' : 'custom');
    // Reset form when dialog opens
    useEffect(() => {
        if (open) {
            set_group_name(default_group_name);
            set_pending_fields([]);
            set_selected_field_type(default_field_type);
            set_active_tab(enable_library ? 'library' : 'custom');
            // Auto-focus group name input only when on custom tab (library tab focuses its own search)
            if (!enable_library) {
                setTimeout(() => {
                    group_name_input_ref.current?.focus();
                }, 100);
            }
        }
    }, [open, default_group_name, default_field_type, enable_library]);
    // Auto-focus group name input when switching to custom tab
    useEffect(() => {
        if (open && active_tab === 'custom') {
            setTimeout(() => {
                group_name_input_ref.current?.focus();
            }, 100);
        }
    }, [open, active_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,
            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,
                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,
                accept_public_files: type === 'HazoCollabFormDoc' ? '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));
    }, []);
    // Convert pending fields to NewFieldDefinition[] and submit
    const handle_confirm = useCallback(() => {
        // Derive group name: custom tab uses typed input, library tab uses first pending entry label
        const trimmed_name = active_tab === 'custom' || !enable_library
            ? group_name.trim()
            : (pending_fields.find(f => f.field_type === 'Group')?.label || pending_fields[0]?.label || '').trim();
        if (!trimmed_name)
            return;
        const new_fields = [];
        for (const field of pending_fields) {
            // Library Group entries represent the group itself, not a child field.
            // Unpack their resolved children as direct children of the new group
            // to avoid nesting groups inside groups.
            if (field.field_type === 'Group') {
                const source_fields = field.source_config?.fields || [];
                for (const child of source_fields) {
                    const child_def = {
                        field_type: (child.component_type || 'HazoCollabFormInputbox'),
                        label: child.label || '',
                        required: child.required === true,
                        source_config: child,
                    };
                    new_fields.push(child_def);
                }
                continue;
            }
            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.accept_public_files && field.accept_public_files !== 'none' && field.field_type !== 'HazoCollabFormDoc') {
                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;
            }
            new_fields.push(definition);
        }
        const group_definition = {
            group_name: trimmed_name,
            fields: new_fields,
        };
        on_confirm(group_definition);
        on_open_change(false);
    }, [group_name, pending_fields, on_confirm, on_open_change, active_tab, enable_library]);
    // Handle cancel
    const handle_cancel = useCallback(() => {
        on_cancel?.();
        on_open_change(false);
    }, [on_cancel, on_open_change]);
    // Determine if confirm button is enabled
    // Library tab: at least one item selected (group name derived from entry)
    // Custom tab: group name required
    const is_confirm_enabled = (active_tab === 'library' && enable_library)
        ? pending_fields.length > 0
        : group_name.trim().length > 0;
    // Determine button text
    const field_count = pending_fields.length;
    const button_text = field_count === 0
        ? 'Add Group'
        : field_count === 1
            ? 'Add Group with 1 Field'
            : `Add Group with ${field_count} Fields`;
    return (_jsx(Dialog, { open: open, onOpenChange: on_open_change, children: _jsxs(DialogContent, { className: "cls_add_group_dialog_content", style: { maxWidth: '800px' }, prevent_close_on_outside_click: true, children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: title }), _jsx(DialogDescription, { children: "Select a group from the library or create a custom one." })] }), _jsxs("div", { className: "space-y-4 py-2", children: [enable_library && (_jsxs("div", { className: "flex border-b", children: [_jsx("button", { type: "button", onClick: () => set_active_tab('library'), className: cn('cls_add_group_tab px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px', active_tab === 'library'
                                        ? 'border-primary text-primary'
                                        : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/50'), children: "Library" }), _jsx("button", { type: "button", onClick: () => set_active_tab('custom'), className: cn('cls_add_group_tab px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px', active_tab === 'custom'
                                        ? 'border-primary text-primary'
                                        : 'border-transparent text-muted-foreground hover:text-foreground hover:border-muted-foreground/50'), children: "Custom" })] })), enable_library && active_tab === 'library' && (_jsx(LibrarySearch, { api_base_url: library_api_base_url, table_name: library_table_name, scope_id: library_scope_id, filter_mode: "both", on_select: handle_library_select })), (!enable_library || active_tab === 'custom') && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "space-y-1.5", children: [_jsxs("label", { htmlFor: "group_name", className: "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", children: ["Group Name ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx("input", { ref: group_name_input_ref, id: "group_name", type: "text", value: group_name, onChange: (e) => set_group_name(e.target.value), onKeyDown: (e) => {
                                                if (e.key === 'Enter' && is_confirm_enabled) {
                                                    e.preventDefault();
                                                    handle_confirm();
                                                }
                                            }, placeholder: "Enter group name...", className: "cls_group_name_input flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" })] }), _jsxs("div", { className: "flex items-center gap-2 py-2", children: [_jsx("div", { className: "h-px flex-1 bg-border" }), _jsx("span", { className: "text-xs text-muted-foreground", children: "Add fields to the group (optional)" }), _jsx("div", { className: "h-px flex-1 bg-border" })] }), _jsx(QuestionInput, { on_add: handle_add_question, auto_focus: false, 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, combobox_components: combobox_components })] }), _jsxs(DialogFooter, { className: "flex-row gap-3", children: [_jsx("button", { type: "button", onClick: handle_confirm, disabled: !is_confirm_enabled, className: cn('cls_add_group_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', is_confirm_enabled
                                ? '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_group_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_group_dialog.js.map