"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdvancedForm = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const useFormValidation_js_1 = require("./hooks/useFormValidation.js");
const useFormAI_js_1 = require("./hooks/useFormAI.js");
const useFormState_js_1 = require("./hooks/useFormState.js");
const useFormPersistence_js_1 = require("./hooks/useFormPersistence.js");
const FormSection_js_1 = require("./components/FormSection.js");
const FormField_js_1 = require("./components/FormField.js");
const FormNavigation_js_1 = require("./components/FormNavigation.js");
const FormProgress_js_1 = require("./components/FormProgress.js");
const ValidationSummary_js_1 = require("./components/ValidationSummary.js");
const AIAssistant_js_1 = require("./components/AIAssistant.js");
const FormToolbar_js_1 = require("./components/FormToolbar.js");
const Modal_js_1 = require("../feedback/Modal.js");
const Button_js_1 = require("../Button.js");
const lucide_react_1 = require("lucide-react");
/**
 * AdvancedForm - AI-Powered Dynamic Form System
 *
 * A comprehensive form builder with:
 * - Dynamic field generation and validation
 * - AI-powered smart validation and suggestions
 * - Multi-step form workflows
 * - Real-time validation and error handling
 * - Auto-save and form persistence
 * - Conditional field visibility
 * - Rich field types and components
 * - Accessibility and internationalization
 * - Export/import capabilities
 * - Advanced theming and customization
 */
const AdvancedForm = ({ schema, initialData = {}, onSubmit, onFieldChange, onValidationChange, enableAI = true, enableAutoSave = true, enableProgressTracking = true, enableValidationSummary = true, multiStep = false, readonly = false, theme = 'default', className = '', validationMode = 'onChange', submitButtonText = 'Submit', aiConfig = {}, persistenceKey, customFields = {}, onError }) => {
    // State management
    const [currentStep, setCurrentStep] = (0, react_1.useState)(0);
    const [isSubmitting, setIsSubmitting] = (0, react_1.useState)(false);
    const [showPreview, setShowPreview] = (0, react_1.useState)(false);
    const [showAIAssistant, setShowAIAssistant] = (0, react_1.useState)(false);
    const [formHistory, setFormHistory] = (0, react_1.useState)([]);
    const [showSettings, setShowSettings] = (0, react_1.useState)(false);
    // Refs
    const formRef = (0, react_1.useRef)(null);
    const fieldRefs = (0, react_1.useRef)({});
    // Custom hooks
    const { formData, setFormData, updateField, resetForm, isDirty, hasChanges } = (0, useFormState_js_1.useFormState)(initialData);
    const { errors, isValid, isValidating, validate, validateField, clearErrors, addError } = (0, useFormValidation_js_1.useFormValidation)(schema, formData, validationMode);
    const { aiSuggestions, aiValidation, isAIProcessing, generateFieldSuggestions, validateWithAI, improveFieldLabels, generateFormDescription } = (0, useFormAI_js_1.useFormAI)(enableAI, aiConfig);
    const { save, load, clear, getHistory, isLoading: isPersistenceLoading } = (0, useFormPersistence_js_1.useFormPersistence)(persistenceKey, enableAutoSave);
    // Computed values
    const sections = (0, react_1.useMemo)(() => {
        if (multiStep && schema.sections) {
            return schema.sections;
        }
        return [{
                id: 'default',
                title: schema.title || 'Form',
                fields: schema.fields,
                description: schema.description
            }];
    }, [schema, multiStep]);
    const currentSection = sections[currentStep];
    const totalSteps = sections.length;
    const progress = multiStep ? ((currentStep + 1) / totalSteps) * 100 : 100;
    const visibleFields = (0, react_1.useMemo)(() => {
        return currentSection.fields.filter(field => {
            if (!field.conditional)
                return true;
            const { dependsOn, condition, value } = field.conditional;
            const dependentValue = formData[dependsOn];
            switch (condition) {
                case 'equals':
                    return dependentValue === value;
                case 'not_equals':
                    return dependentValue !== value;
                case 'contains':
                    return Array.isArray(dependentValue) && dependentValue.includes(value);
                case 'not_empty':
                    return dependentValue && dependentValue !== '';
                case 'empty':
                    return !dependentValue || dependentValue === '';
                case 'greater_than':
                    return Number(dependentValue) > Number(value);
                case 'less_than':
                    return Number(dependentValue) < Number(value);
                default:
                    return true;
            }
        });
    }, [currentSection.fields, formData]);
    // Auto-save functionality
    (0, react_1.useEffect)(() => {
        if (enableAutoSave && isDirty && persistenceKey) {
            const autoSaveTimer = setTimeout(() => {
                save(formData);
            }, 2000);
            return () => clearTimeout(autoSaveTimer);
        }
    }, [formData, isDirty, enableAutoSave, persistenceKey, save]);
    // Form validation
    (0, react_1.useEffect)(() => {
        if (validationMode === 'onChange' && hasChanges) {
            validate();
        }
    }, [formData, validate, validationMode, hasChanges]);
    // AI validation
    (0, react_1.useEffect)(() => {
        if (enableAI && aiConfig.autoValidate && hasChanges) {
            const aiValidationTimer = setTimeout(() => {
                validateWithAI(formData);
            }, 1000);
            return () => clearTimeout(aiValidationTimer);
        }
    }, [formData, enableAI, aiConfig.autoValidate, hasChanges, validateWithAI]);
    // Load persisted data on mount
    (0, react_1.useEffect)(() => {
        if (persistenceKey) {
            const loadData = async () => {
                try {
                    const persistedData = await load();
                    if (persistedData) {
                        setFormData(persistedData);
                    }
                }
                catch (error) {
                    console.warn('Failed to load persisted form data:', error);
                }
            };
            loadData();
        }
    }, [persistenceKey, load, setFormData]);
    // Event handlers
    const handleFieldChange = (0, react_1.useCallback)((fieldId, value) => {
        updateField(fieldId, value);
        onFieldChange?.(fieldId, value, formData);
        // AI suggestions for related fields
        if (enableAI && aiConfig.suggestRelatedFields) {
            generateFieldSuggestions(fieldId, value, formData);
        }
        // Clear field-specific errors when value changes
        if (errors[fieldId]) {
            clearErrors(fieldId);
        }
    }, [updateField, onFieldChange, formData, enableAI, aiConfig.suggestRelatedFields, generateFieldSuggestions, errors, clearErrors]);
    const handleFieldBlur = (0, react_1.useCallback)((fieldId) => {
        if (validationMode === 'onBlur' || validationMode === 'onSubmit') {
            validateField(fieldId);
        }
    }, [validationMode, validateField]);
    const handleSubmit = (0, react_1.useCallback)(async (event) => {
        event.preventDefault();
        if (readonly)
            return;
        setIsSubmitting(true);
        try {
            // Validate entire form
            const isFormValid = await validate();
            if (!isFormValid) {
                // Focus first error field
                const firstErrorField = Object.keys(errors)[0];
                if (firstErrorField && fieldRefs.current[firstErrorField]) {
                    fieldRefs.current[firstErrorField].focus();
                }
                return;
            }
            // AI validation if enabled
            if (enableAI && aiConfig.validateOnSubmit) {
                const aiResult = await validateWithAI(formData);
                if (aiResult && !aiResult.isValid) {
                    aiResult.errors.forEach(error => {
                        addError(error.field, error.message);
                    });
                    return;
                }
            }
            // Save to history
            setFormHistory(prev => [...prev, { ...formData, timestamp: new Date() }]);
            // Submit form
            await onSubmit(formData);
            // Clear form if successful
            if (schema.clearOnSubmit) {
                resetForm();
            }
        }
        catch (error) {
            console.error('Form submission error:', error);
            onError?.(error);
        }
        finally {
            setIsSubmitting(false);
        }
    }, [
        readonly,
        validate,
        errors,
        enableAI,
        aiConfig.validateOnSubmit,
        aiConfig.suggestRelatedFields,
        validateWithAI,
        formData,
        addError,
        onSubmit,
        schema.clearOnSubmit,
        resetForm,
        onError
    ]);
    const handleStepNavigation = (0, react_1.useCallback)((direction) => {
        if (direction === 'next' && currentStep < totalSteps - 1) {
            // Validate current step before proceeding
            const currentStepValid = visibleFields.every(field => !errors[field.id]);
            if (currentStepValid) {
                setCurrentStep(prev => prev + 1);
            }
            else {
                // Focus first error in current step
                const firstError = visibleFields.find(field => errors[field.id]);
                if (firstError && fieldRefs.current[firstError.id]) {
                    fieldRefs.current[firstError.id].focus();
                }
            }
        }
        else if (direction === 'prev' && currentStep > 0) {
            setCurrentStep(prev => prev - 1);
        }
    }, [currentStep, totalSteps, visibleFields, errors]);
    const handleExport = (0, react_1.useCallback)(() => {
        const exportData = {
            schema,
            data: formData,
            timestamp: new Date().toISOString(),
            version: '1.0'
        };
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {
            type: 'application/json'
        });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `form-data-${Date.now()}.json`;
        link.click();
        URL.revokeObjectURL(url);
    }, [schema, formData]);
    const handleImport = (0, react_1.useCallback)((event) => {
        const file = event.target.files?.[0];
        if (!file)
            return;
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const importData = JSON.parse(e.target?.result);
                if (importData.data) {
                    setFormData(importData.data);
                }
            }
            catch (error) {
                console.error('Failed to import form data:', error);
                onError?.(new Error('Invalid import file format'));
            }
        };
        reader.readAsText(file);
    }, [setFormData, onError]);
    // Render functions
    const renderField = (field) => {
        const fieldError = errors[field.id];
        const fieldSuggestion = aiSuggestions[field.id];
        const CustomFieldComponent = customFields[field.type];
        return ((0, jsx_runtime_1.jsx)("div", { className: "form-field-wrapper", children: CustomFieldComponent ? ((0, jsx_runtime_1.jsx)(CustomFieldComponent, { field: field, value: formData[field.id], onChange: (value) => handleFieldChange(field.id, value), onBlur: () => handleFieldBlur(field.id), error: fieldError, suggestion: fieldSuggestion, readonly: readonly, ref: (el) => {
                    if (el)
                        fieldRefs.current[field.id] = el;
                } })) : ((0, jsx_runtime_1.jsx)(FormField_js_1.FormField, { field: field, value: formData[field.id], onChange: (value) => handleFieldChange(field.id, value), onBlur: () => handleFieldBlur(field.id), error: fieldError, suggestion: fieldSuggestion, readonly: readonly, theme: theme, ref: (el) => {
                    if (el)
                        fieldRefs.current[field.id] = el;
                } })) }, field.id));
    };
    const renderCurrentStep = () => {
        if (!currentSection)
            return null;
        return ((0, jsx_runtime_1.jsx)(FormSection_js_1.FormSection, { section: currentSection, fields: visibleFields, formData: formData, errors: errors, readonly: readonly, theme: theme, onFieldChange: handleFieldChange, onFieldBlur: handleFieldBlur, renderField: renderField }));
    };
    const renderSubmitButton = () => {
        const isLastStep = !multiStep || currentStep === totalSteps - 1;
        if (!isLastStep) {
            return ((0, jsx_runtime_1.jsx)(Button_js_1.Button, { type: "button", onClick: () => handleStepNavigation('next'), disabled: readonly, className: "btn-primary", children: "Next Step" }));
        }
        return ((0, jsx_runtime_1.jsx)(Button_js_1.Button, { type: "submit", disabled: readonly || isSubmitting || !isValid, loading: isSubmitting, className: "btn-primary", children: isSubmitting ? 'Submitting...' : submitButtonText }));
    };
    return ((0, jsx_runtime_1.jsxs)("div", { className: `advanced-form ${theme} ${className}`, children: [(0, jsx_runtime_1.jsx)(FormToolbar_js_1.FormToolbar, { onSave: () => save(formData), onLoad: load, onClear: resetForm, onExport: handleExport, onImport: handleImport, onPreview: () => setShowPreview(true), onSettings: () => setShowSettings(true), onAIAssistant: () => setShowAIAssistant(true), isDirty: isDirty, isLoading: isPersistenceLoading, readonly: readonly, enableAI: enableAI }), enableProgressTracking && multiStep && ((0, jsx_runtime_1.jsx)(FormProgress_js_1.FormProgress, { currentStep: currentStep + 1, totalSteps: totalSteps, progress: progress, sections: sections, onStepClick: (step) => setCurrentStep(step), canNavigate: !readonly })), enableValidationSummary && Object.keys(errors).length > 0 && ((0, jsx_runtime_1.jsx)(ValidationSummary_js_1.ValidationSummary, { errors: errors, onErrorClick: (fieldId) => {
                    const field = fieldRefs.current[fieldId];
                    if (field) {
                        field.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        field.focus();
                    }
                } })), aiValidation && !aiValidation.isValid && ((0, jsx_runtime_1.jsx)("div", { className: "ai-validation-panel bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6", children: (0, jsx_runtime_1.jsxs)("div", { className: "flex items-start space-x-3", children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Brain, { className: "w-5 h-5 text-yellow-600 mt-0.5" }), (0, jsx_runtime_1.jsxs)("div", { className: "flex-1", children: [(0, jsx_runtime_1.jsx)("h4", { className: "font-medium text-yellow-800 mb-2", children: "AI Validation Insights" }), (0, jsx_runtime_1.jsx)("ul", { className: "text-sm text-yellow-700 space-y-1", children: aiValidation.suggestions.map((suggestion, index) => ((0, jsx_runtime_1.jsxs)("li", { children: ["\u2022 ", suggestion] }, index))) })] })] }) })), (0, jsx_runtime_1.jsxs)("form", { ref: formRef, onSubmit: handleSubmit, className: "advanced-form-content", noValidate: true, children: [renderCurrentStep(), (0, jsx_runtime_1.jsx)(FormNavigation_js_1.FormNavigation, { currentStep: currentStep, totalSteps: totalSteps, canGoNext: visibleFields.every(field => !errors[field.id]), canGoPrev: currentStep > 0, onNext: () => handleStepNavigation('next'), onPrev: () => handleStepNavigation('prev'), onSubmit: handleSubmit, submitButton: renderSubmitButton(), readonly: readonly, multiStep: multiStep })] }), showAIAssistant && enableAI && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showAIAssistant, onClose: () => setShowAIAssistant(false), title: "AI Form Assistant", size: "lg", children: (0, jsx_runtime_1.jsx)(AIAssistant_js_1.AIAssistant, { formData: formData, schema: schema, errors: errors, onSuggestionApply: (fieldId, value) => {
                        handleFieldChange(fieldId, value);
                        setShowAIAssistant(false);
                    }, onLabelImprovement: (fieldId, newLabel) => {
                        // Update field label in schema
                    }, onFormImprovement: (suggestions) => {
                        // Apply form improvements
                    } }) })), showPreview && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showPreview, onClose: () => setShowPreview(false), title: "Form Preview", size: "xl", children: (0, jsx_runtime_1.jsxs)("div", { className: "form-preview", children: [(0, jsx_runtime_1.jsxs)("div", { className: "preview-data", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-4", children: "Form Data" }), (0, jsx_runtime_1.jsx)("pre", { className: "bg-gray-100 p-4 rounded text-sm overflow-auto", children: JSON.stringify(formData, null, 2) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "preview-validation mt-6", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-4", children: "Validation Status" }), (0, jsx_runtime_1.jsx)("div", { className: `validation-badge ${isValid ? 'valid' : 'invalid'}`, children: isValid ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Check, { className: "w-4 h-4" }), " Form is valid"] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(lucide_react_1.AlertCircle, { className: "w-4 h-4" }), " ", Object.keys(errors).length, " validation errors"] })) })] })] }) })), showSettings && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showSettings, onClose: () => setShowSettings(false), title: "Form Settings", size: "md", children: (0, jsx_runtime_1.jsxs)("div", { className: "form-settings space-y-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "setting-group", children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium mb-2", children: "Validation Mode" }), (0, jsx_runtime_1.jsxs)("select", { className: "form-select w-full", value: validationMode, onChange: (e) => {
                                        // Update validation mode
                                    }, children: [(0, jsx_runtime_1.jsx)("option", { value: "onChange", children: "On Change" }), (0, jsx_runtime_1.jsx)("option", { value: "onBlur", children: "On Blur" }), (0, jsx_runtime_1.jsx)("option", { value: "onSubmit", children: "On Submit" })] })] }), (0, jsx_runtime_1.jsx)("div", { className: "setting-group", children: (0, jsx_runtime_1.jsxs)("label", { className: "flex items-center space-x-2", children: [(0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: enableAutoSave, onChange: (e) => {
                                            // Update auto-save setting
                                        } }), (0, jsx_runtime_1.jsx)("span", { children: "Enable Auto-save" })] }) }), (0, jsx_runtime_1.jsx)("div", { className: "setting-group", children: (0, jsx_runtime_1.jsxs)("label", { className: "flex items-center space-x-2", children: [(0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: enableAI, onChange: (e) => {
                                            // Update AI setting
                                        } }), (0, jsx_runtime_1.jsx)("span", { children: "Enable AI Assistant" })] }) })] }) })), isValidating && ((0, jsx_runtime_1.jsx)("div", { className: "form-loading-overlay", children: (0, jsx_runtime_1.jsxs)("div", { className: "loading-spinner", children: [(0, jsx_runtime_1.jsx)("div", { className: "spinner" }), (0, jsx_runtime_1.jsx)("span", { children: "Validating form..." })] }) })), isAIProcessing && ((0, jsx_runtime_1.jsxs)("div", { className: "ai-processing-indicator", children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Brain, { className: "w-4 h-4 animate-pulse" }), (0, jsx_runtime_1.jsx)("span", { children: "AI is analyzing your form..." })] }))] }));
};
exports.AdvancedForm = AdvancedForm;
exports.default = exports.AdvancedForm;
//# sourceMappingURL=AdvancedForm.js.map