/**
 * Dialog component for editing an existing group's name and fields
 * Pre-populated with current group values
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } 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 { FileSettings } from '../shared/file_settings/index.js';
/**
 * Generate a unique ID for pending fields
 */
function generate_id() {
    return `pending_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
/**
 * Convert NewFieldDefinition to PendingFieldEntry
 */
function field_definition_to_pending(field, index) {
    return {
        id: generate_id(),
        label: field.label,
        field_type: field.field_type,
        required: field.required || false,
        accept_public_files: field.accept_public_files || 'none',
        options: field.options,
        date_config: field.date_config,
        checkbox_config: field.checkbox_config,
        is_expanded: false,
    };
}
/**
 * HazoEditGroupDialog - Dialog for editing an existing group's name and fields
 *
 * Opens a modal dialog that allows users to:
 * - Edit the group name
 * - Edit existing fields (label, type, options)
 * - Add new fields to the group
 * - Remove fields from the group
 * - Reorder fields via drag and drop
 * - Delete the entire group
 *
 * 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 HazoEditGroupDialog({ open, on_open_change, group_data, on_confirm, on_cancel, on_delete, title = 'Edit Group', exclude_types = [], dialog_components, combobox_components, }) {
    // 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(group_data.label);
    const group_name_input_ref = useRef(null);
    // File settings state
    const [accept_public_files, set_accept_public_files] = useState(group_data.accept_public_files ?? 'none');
    const [accept_private_files, set_accept_private_files] = useState(group_data.accept_private_files ?? 'none');
    // Pending fields state - initialized from group_data.fields
    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);
    // Reset form when dialog opens or group_data changes
    useEffect(() => {
        if (open) {
            set_group_name(group_data.label);
            set_accept_public_files(group_data.accept_public_files ?? 'none');
            set_accept_private_files(group_data.accept_private_files ?? 'none');
            // Convert existing fields to pending entries
            const initial_fields = group_data.fields.map((field, index) => field_definition_to_pending(field, index));
            set_pending_fields(initial_fields);
            set_selected_field_type(default_field_type);
            // Auto-focus the group name input
            setTimeout(() => {
                group_name_input_ref.current?.focus();
            }, 100);
        }
    }, [open, group_data, default_field_type]);
    // ========================================
    // 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]);
    }, []);
    // 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(() => {
        const trimmed_name = group_name.trim();
        if (!trimmed_name)
            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.accept_public_files && field.accept_public_files !== 'none' && field.field_type !== 'HazoCollabFormDoc' && field.field_type !== 'Group') {
                definition.accept_public_files = field.accept_public_files;
            }
            return definition;
        });
        const updated_group = {
            id: group_data.id,
            label: trimmed_name,
            fields: new_fields,
            accept_public_files,
            accept_private_files,
            private_files_permission: group_data.private_files_permission,
        };
        on_confirm(updated_group);
        on_open_change(false);
    }, [group_data.id, group_data.private_files_permission, group_name, pending_fields, accept_public_files, accept_private_files, on_confirm, on_open_change]);
    // Handle cancel
    const handle_cancel = useCallback(() => {
        on_cancel?.();
        on_open_change(false);
    }, [on_cancel, on_open_change]);
    // Handle delete
    const handle_delete = useCallback(() => {
        on_delete?.();
        on_open_change(false);
    }, [on_delete, on_open_change]);
    // Determine if confirm button is enabled
    const is_confirm_enabled = group_name.trim().length > 0;
    // Determine button text
    const field_count = pending_fields.length;
    const button_text = 'Save Changes';
    return (_jsx(Dialog, { open: open, onOpenChange: on_open_change, children: _jsxs(DialogContent, { className: "cls_edit_group_dialog_content", style: { maxWidth: '800px' }, prevent_close_on_outside_click: true, children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: title }), _jsx(DialogDescription, { children: "Edit the group name and its fields." })] }), _jsxs("div", { className: "space-y-4 py-2", 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" })] }), _jsx(FileSettings, { accept_public_files: accept_public_files, on_accept_public_files_change: set_accept_public_files, accept_private_files: accept_private_files, on_accept_private_files_change: (v) => set_accept_private_files(v), id_prefix: "edit-group-" }), _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: "Edit or add fields" }), _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 justify-between", children: [on_delete && (_jsx("button", { type: "button", onClick: handle_delete, className: "cls_edit_group_dialog_delete inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium text-destructive ring-offset-background transition-colors hover:bg-destructive/10 hover:text-destructive focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", children: "Delete Group" })), _jsxs("div", { className: "flex gap-3", children: [_jsx("button", { type: "button", onClick: handle_confirm, disabled: !is_confirm_enabled, className: cn('cls_edit_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_edit_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_edit_group_dialog.js.map