<template>
    <div class="dynamic-form-container">
        <div class="dynamic-form" :class="{ 'readonly': readOnly, 'edit': !readOnly }">
            <!-- Form header with icon and title -->
            <div v-if="shouldShowFormHeader" class="form-header">
                <div v-if="formData.icon" class="form-icon">
                    <span class="material-symbols-outlined">{{ formData.icon }}</span>
                </div>
                <div class="form-title">{{ formData.title || formData.name }}</div>
            </div>

            <!-- Form fields (alleen tonen als NIET read-only) -->
            <div v-if="!readOnly" class="form-fields">
                <template v-if="Array.isArray(formData.fields)">
                    <form-field
                        v-for="field in formData.fields"
                        :key="field.id || field.name"
                        :field="field"
                        :field-id="field.id || field.name"
                        :model-value="localFormValues[field.id || field.name]"
                        @update:model-value="updateFieldValue(field.id || field.name, $event)"
                        @open-privacy-modal="openPrivacyModal"
                        @open-terms-modal="openTermsModal"
                        @keydown-enter="handleEnterKey"
                    />
                </template>
                <template v-else-if="typeof formData.fields === 'object'">
                    <form-field
                        v-for="(field, fieldId) in formData.fields"
                        :key="fieldId"
                        :field="field"
                        :field-id="fieldId"
                        :model-value="localFormValues[fieldId]"
                        @update:model-value="updateFieldValue(fieldId, $event)"
                        @open-privacy-modal="openPrivacyModal"
                        @open-terms-modal="openTermsModal"
                        @keydown-enter="handleEnterKey"
                    />
                </template>
            </div>

            <!-- Form actions (only show if not hidden and not read-only) -->
            <div v-if="!hideActions && !readOnly" class="form-actions" :class="{ 'with-send-button': showSendButton }">
                <!-- Send button mode (ChatInput styling) -->
                <template v-if="showSendButton">
                    <button 
                        type="button"
                        @click="handleSendSubmit"
                        class="send-btn"
                        :disabled="isSubmittingForm || !isFormValid"
                        :title="sendButtonText"
                    >
                        <span v-if="isSubmittingForm" class="loading-spinner">⏳</span>
                        <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                        </svg>
                    </button>
                </template>
                
                <!-- Standard buttons mode -->
                <template v-else>
                    <button 
                        type="button" 
                        @click="handleCancel"
                        class="btn btn-secondary"
                        :disabled="isSubmitting"
                    >
                        Annuleren
                    </button>
                    <button 
                        type="button" 
                        @click="handleSubmit"
                        class="btn btn-primary"
                        :disabled="isSubmitting || !isFormValid"
                    >
                        <span v-if="isSubmitting">Verzenden...</span>
                        <span v-else>Versturen</span>
                    </button>
                </template>
            </div>

            <!-- Read-only form display -->
            <div v-if="readOnly" class="form-readonly">
                <div 
                    v-for="(field, fieldId) in getFieldsForDisplay()" 
                    :key="fieldId" 
                    class="form-field-readonly"
                >
                    <div class="field-label">{{ field.name }}:</div>
                    <div class="field-value" :class="{'text-value': field.type === 'text', 'boolean-value': field.type === 'boolean'}">
                        <span v-if="field.type === 'boolean'" v-html="formatFieldValue(fieldId, field)"></span>
                        <span v-else>{{ formatFieldValue(fieldId, field) }}</span>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
import FormField from './FormField.vue';
import { useIconManager } from '../js/composables/useIconManager.js';
import { injectContentModal } from '../js/composables/useContentModal.js';

export default {
    name: 'DynamicForm',
    components: {
        'form-field': FormField
    },
    setup(props) {
        const { watchIcon, loadIcons } = useIconManager();
        const contentModal = injectContentModal();
        
        // Watch formData.icon for automatic icon loading
        watchIcon(() => props.formData?.icon);
        
        // Preload boolean icons
        loadIcons(['check_circle', 'cancel']);
        
        return {
            contentModal
        };
    },
    props: {
        formData: {
            type: Object,
            required: true,
            validator: (formData) => {
                // Controleer eerst of formData een geldig object is
                if (!formData || typeof formData !== 'object') {
                    console.error('FormData is niet een geldig object');
                    return false;
                }

                // Controleer of er een titel of naam is
                if (!formData.title && !formData.name) {
                    console.error('FormData heeft geen title of name');
                    return false;
                }

                // Controleer of er velden zijn
                if (!formData.fields) {
                    console.error('FormData heeft geen fields eigenschap');
                    return false;
                }

                // Controleer of velden een array of object zijn
                if (!Array.isArray(formData.fields) && typeof formData.fields !== 'object') {
                    console.error('FormData.fields is geen array of object');
                    return false;
                }

                console.log('FormData is geldig:', formData);
                return true;
            }
        },
        formValues: {
            type: Object,
            default: () => ({})
        },
        isSubmitting: {
            type: Boolean,
            default: false
        },
        readOnly: {
            type: Boolean,
            default: false
        },
        hideActions: {
            type: Boolean,
            default: false
        },
        apiPrefix: {
            type: String,
            required: true
        },
        showSendButton: {
            type: Boolean,
            default: false
        },
        sendButtonText: {
            type: String,
            default: 'Verstuur formulier'
        },
        isSubmittingForm: {
            type: Boolean,
            default: false
        }
    },
    emits: ['submit', 'cancel', 'update:formValues', 'form-enter-pressed', 'form-send-submit'],
    data() {
        return {
            localFormValues: { ...this.formValues }
        };
    },
    computed: {
        isFormValid() {
            // Basic validation - check required fields
            const missingFields = [];

            if (Array.isArray(this.formData.fields)) {
                // Valideer array-gebaseerde velden
                this.formData.fields.forEach(field => {
                    const fieldId = field.id || field.name;
                    if (field.required) {
                        const value = this.localFormValues[fieldId];
                        // Voor boolean velden is false een geldige waarde
                        if (field.type === 'boolean') {
                            // Boolean velden zijn altijd geldig als ze een boolean waarde hebben
                            if (typeof value !== 'boolean') {
                                missingFields.push(field.name);
                            }
                        } else {
                            // Bestaande validatie voor andere veldtypen
                            if (value === undefined || value === null || 
                                (typeof value === 'string' && !value.trim()) ||
                                (Array.isArray(value) && value.length === 0)) {
                                missingFields.push(field.name);
                            }
                        }
                    }
                });
            } else {
                // Valideer object-gebaseerde velden
                Object.entries(this.formData.fields).forEach(([fieldId, field]) => {
                    if (field.required) {
                        const value = this.localFormValues[fieldId];
                        // Voor boolean velden is false een geldige waarde
                        if (field.type === 'boolean') {
                            // Boolean velden zijn altijd geldig als ze een boolean waarde hebben
                            if (typeof value !== 'boolean') {
                                missingFields.push(field.name);
                            }
                        } else {
                            // Bestaande validatie voor andere veldtypen
                            if (value === undefined || value === null || 
                                (typeof value === 'string' && !value.trim()) ||
                                (Array.isArray(value) && value.length === 0)) {
                                missingFields.push(field.name);
                            }
                        }
                    }
                });
            }

            return missingFields.length === 0;
        },
        // Title display mode configuration
        titleDisplayMode() {
            console.log('Title display mode:', window.chatConfig?.form_title_display || 'Full Title');
            return window.chatConfig?.form_title_display || 'Full Title';
        },
        // Determine if form header should be shown
        shouldShowFormHeader() {
            const hasContent = this.formData.title || this.formData.name || this.formData.icon;
            return hasContent && this.titleDisplayMode !== 'No Title';
        }
    },
    watch: {
        formValues: {
            handler(newValues) {
                // Gebruik een vlag om recursieve updates te voorkomen
                if (JSON.stringify(newValues) !== JSON.stringify(this.localFormValues)) {
                    this.localFormValues = JSON.parse(JSON.stringify(newValues));
                    // Proactief alle boolean velden corrigeren na externe wijziging
                    this.$nextTick(() => {
                        this.initializeBooleanFields();
                    });
                }
            },
            deep: true
        },
        formData: {
            handler() {
                // Herinitialiseer boolean velden wanneer form structuur verandert
                this.$nextTick(() => {
                    this.initializeBooleanFields();
                });
            },
            deep: true
        },
        localFormValues: {
            handler(newValues) {
                // Gebruik een vlag om recursieve updates te voorkomen
                if (JSON.stringify(newValues) !== JSON.stringify(this.formValues)) {
                    this.$emit('update:formValues', JSON.parse(JSON.stringify(newValues)));
                }
            },
            deep: true
        },
    },
    created() {
        // Icon loading is now handled automatically by useIconManager composable
    },
    mounted() {
        // Proactief alle boolean velden initialiseren bij het laden
        this.initializeBooleanFields();
        
        // Auto-focus on first form field for better UX
        this.$nextTick(() => {
            this.focusFirstField();
        });
    },
    methods: {
        // Proactieve initialisatie van alle boolean velden
        initializeBooleanFields() {
            const updatedValues = { ...this.localFormValues };
            let hasChanges = false;
            
            // Behandel alle boolean velden in het formulier
            const fields = Array.isArray(this.formData.fields) 
                ? this.formData.fields 
                : Object.entries(this.formData.fields).map(([id, field]) => ({ ...field, id }));
            
            fields.forEach(field => {
                const fieldId = field.id || field.name;
                if (field.type === 'boolean') {
                    const currentValue = updatedValues[fieldId];
                    // Initialiseer als de waarde undefined, null, of een lege string is
                    if (currentValue === undefined || currentValue === null || currentValue === '') {
                        updatedValues[fieldId] = field.default === true ? true : false;
                        hasChanges = true;
                    } else if (typeof currentValue !== 'boolean') {
                        // Converteer andere waarden naar boolean
                        updatedValues[fieldId] = Boolean(currentValue);
                        hasChanges = true;
                    }
                }
            });
            
            // Update alleen als er wijzigingen zijn
            if (hasChanges) {
                this.localFormValues = updatedValues;
            }
        },

        updateFieldValue(fieldId, value) {
            // Zoek het veld om het type te bepalen
            let field = null;
            if (Array.isArray(this.formData.fields)) {
                field = this.formData.fields.find(f => (f.id || f.name) === fieldId);
            } else {
                field = this.formData.fields[fieldId];
            }
            
            // Type conversie voor boolean velden
            let processedValue = value;
            if (field && field.type === 'boolean') {
                processedValue = Boolean(value);
            }
            
            // Update lokale waarde
            this.localFormValues = {
                ...this.localFormValues,
                [fieldId]: processedValue
            };
            
            // Na elke field update, controleer alle boolean velden
            this.$nextTick(() => {
                this.initializeBooleanFields();
            });
        },

        handleSubmit() {
            // Eerst proactief alle boolean velden corrigeren
            this.initializeBooleanFields();
            
            // Wacht tot updates zijn verwerkt, dan valideer en submit
            this.$nextTick(() => {
                // Basic validation
                const missingFields = [];

                if (Array.isArray(this.formData.fields)) {
                    // Valideer array-gebaseerde velden
                    this.formData.fields.forEach(field => {
                        const fieldId = field.id || field.name;
                        if (field.required) {
                            const value = this.localFormValues[fieldId];
                            // Voor boolean velden is false een geldige waarde
                            if (field.type === 'boolean') {
                                // Boolean velden zijn altijd geldig als ze een boolean waarde hebben
                                if (typeof value !== 'boolean') {
                                    missingFields.push(field.name);
                                }
                            } else {
                                // Bestaande validatie voor andere veldtypen
                                if (value === undefined || value === null || 
                                    (typeof value === 'string' && !value.trim()) ||
                                    (Array.isArray(value) && value.length === 0)) {
                                    missingFields.push(field.name);
                                }
                            }
                        }
                    });
                } else {
                    // Valideer object-gebaseerde velden
                    Object.entries(this.formData.fields).forEach(([fieldId, field]) => {
                        if (field.required) {
                            const value = this.localFormValues[fieldId];
                            // Voor boolean velden is false een geldige waarde
                            if (field.type === 'boolean') {
                                // Boolean velden zijn altijd geldig als ze een boolean waarde hebben
                                if (typeof value !== 'boolean') {
                                    missingFields.push(field.name);
                                }
                            } else {
                                // Bestaande validatie voor andere veldtypen
                                if (value === undefined || value === null || 
                                    (typeof value === 'string' && !value.trim()) ||
                                    (Array.isArray(value) && value.length === 0)) {
                                    missingFields.push(field.name);
                                }
                            }
                        }
                    });
                }

                if (missingFields.length > 0) {
                    alert(`De volgende velden zijn verplicht: ${missingFields.join(', ')}`);
                    return;
                }

                // Emit submit event
                this.$emit('submit', this.localFormValues);
            });
        },

        handleCancel() {
            this.$emit('cancel');
        },

        handleSendSubmit() {
            // Eerst proactief alle boolean velden corrigeren
            this.initializeBooleanFields();
            
            // Wacht tot updates zijn verwerkt, dan emit de form values
            this.$nextTick(() => {
                this.$emit('form-send-submit', this.localFormValues);
            });
        },

        getFieldsForDisplay() {
            // Voor read-only weergave
            if (Array.isArray(this.formData.fields)) {
                const fieldsObj = {};
                this.formData.fields.forEach(field => {
                    const fieldId = field.id || field.name;
                    fieldsObj[fieldId] = field;
                });
                return fieldsObj;
            }
            return this.formData.fields;
        },

        formatFieldValue(fieldId, field) {
            const value = this.localFormValues[fieldId];
            
            if (value === undefined || value === null) {
                return '-';
            }

            // Format different field types
            if (field.type === 'boolean') {
                const iconName = value ? 'check_circle' : 'cancel';
                const label = value ? 'Ja' : 'Nee';
                const cssClass = value ? 'boolean-true' : 'boolean-false';
                
                return `<span class="material-symbols-outlined boolean-icon ${cssClass}" 
                              aria-label="${label}" 
                              title="${label}">
                            ${iconName}
                        </span>`;
            } else if (field.type === 'enum' && !value && field.default) {
                return field.default;
            }

            return value.toString();
        },

        // Modal handling methods
        openPrivacyModal() {
            this.loadContent('dpa');
        },

        openTermsModal() {
            this.loadContent('terms');
        },

        closeModal() {
            this.contentModal.hideModal();
        },

        retryLoad() {
            // Retry loading the last requested content type
            const currentTitle = this.contentModal.modalState.title.toLowerCase();
            if (currentTitle.includes('dpa')) {
                this.loadContent('dpa');
            } else if (currentTitle.includes('terms')) {
                this.loadContent('terms');
            }
        },

        async loadContent(contentType) {
            const title = contentType === 'dpa' ? 'Data Privacy Agreement' : 'Terms & Conditions';
            const contentUrl = `${this.apiPrefix}/${contentType}`;
            
            // Use the composable to show modal and load content
            await this.contentModal.showModal({
                title: title,
                contentUrl: contentUrl
            });
        },

        // Handle Enter key press in form fields
        handleEnterKey(event) {
            console.log('DynamicForm: Enter event received, emitting form-enter-pressed');
            // Prevent default form submission
            event.preventDefault();
            // Emit event to parent (ChatInput) to trigger send
            this.$emit('form-enter-pressed');
        },

        // Focus management - auto-focus on first form field
        focusFirstField() {
            if (this.readOnly) return; // Don't focus in read-only mode
            
            // Find the first focusable input element
            const firstInput = this.$el.querySelector('input:not([type="hidden"]):not([type="radio"]):not([type="checkbox"]), textarea, select');
            if (firstInput) {
                firstInput.focus();
            }
        }
    }
};
</script>

<style scoped>
/* Dynamisch formulier stijlen */
.dynamic-form-container {
    overflow: hidden;
    transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
    transform: translateY(0);
    opacity: 1;
}

.message .dynamic-form-container {
    width: 100%;
    max-width: none;
}

.dynamic-form {
    background: var(--human-message-background);
    border-radius: 8px;
    box-shadow: 0 2px 15px rgba(0,0,0,0.1);
    box-sizing: border-box;
    max-width: 100%;
    padding: 12px; /* lucht binnen de form */
}

.form-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--human-message-text-color);
}

.dynamic-form.readonly .form-header {
    border-bottom: none; /* alle borders weg in readonly */
    padding-bottom: 0;
    margin-bottom: 8px;
}

.form-icon {
    margin-right: 10px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--human-message-text-color);
}

.dynamic-form.readonly .form-icon {
    color: #777;
}

.form-title {
    font-size: 1.2rem;
    font-weight: 600;
    color: var(--human-message-text-color);
}

.dynamic-form.readonly .form-title {
    color: #777;
}

.form-fields {
    display: grid;
    grid-template-columns: 1fr;
    gap: 15px;
    margin-bottom: 20px;
}

.form-field {
    margin-bottom: 5px;
}

.form-field label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-field input,
.form-field select,
.form-field textarea {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 0.9rem;
    background-color: #fff;
}

.form-field input:focus,
.form-field select:focus,
.form-field textarea:focus {
    outline: none;
    border-color: #4a90e2;
    box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
}

.form-field textarea {
    min-height: 80px;
    resize: vertical;
}

.checkbox-container {
    display: flex;
    align-items: center;
}

.checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
    width: auto;
    margin-right: 8px;
}

.checkbox-text {
    font-size: 0.9rem;
}

.field-description {
    display: block;
    margin-top: 5px;
    font-size: 0.8rem;
    color: #777;
    line-height: 1.4;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 12px; /* iets meer ruimte boven de send-knop */
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
    transition: background-color 0.2s;
}

.btn-primary {
    background-color: #4a90e2;
    color: white;
}

.btn-primary:hover:not(:disabled) {
    background-color: #357abd;
}

.btn-secondary {
    background-color: #6c757d;
    color: white;
}

.btn-secondary:hover:not(:disabled) {
    background-color: #545b62;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.form-toggle-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 5px;
    color: #555;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.form-toggle-btn:hover {
    background-color: #f0f0f0;
}

.form-toggle-btn.active {
    color: #4a90e2;
    background-color: rgba(74, 144, 226, 0.1);
}

.required {
    color: #e53935;
    margin-left: 2px;
}

/* Read-only form styling */
.form-readonly {
    padding: 8px 0; /* compacter binnen bubble */
    box-sizing: border-box;
    max-width: 100%;
}

.form-field-readonly {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 6px; /* compacter */
    padding-bottom: 6px;
    line-height: 1.3; /* iets compacter */
    box-sizing: border-box;
    max-width: 100%;
}

.dynamic-form.readonly .form-field-readonly {
    border-bottom: none; /* alle borders weg in readonly */
}

.field-label {
    flex: 0 0 30%;
    font-weight: 500;
    padding-right: 8px;
    box-sizing: border-box;
    max-width: 100%;
}

.field-value {
    flex: 1;
    overflow-wrap: anywhere; /* desktop: meerregelig zonder overflow */
    box-sizing: border-box;
    max-width: 100%;
}

.text-value {
    white-space: pre-wrap;
}

/* Responsive aanpassingen voor read-only binnen message bubbles */
@media (min-width: 768px) {
  /* Desktop en groter: geen ellipsis, laat tekst wrappen */
  .dynamic-form.readonly .field-label,
  .dynamic-form.readonly .field-value {
    white-space: normal;
    overflow: visible;
    text-overflow: clip;
  }
}

@media (max-width: 767.98px) {
  /* Mobiel: label boven waarde, vet label, ellipsis op één regel */
  .dynamic-form.readonly .form-field-readonly {
    display: block;
    border-bottom: none; /* alle borders weg in readonly */
  }
  .dynamic-form.readonly .field-label {
    display: block;
    font-weight: 600;
    margin-bottom: 3px; /* kleine afstand tussen label en waarde */
    padding-right: 0;
    flex: none;
  }
  .dynamic-form.readonly .field-value {
    display: block;
  }
  .dynamic-form.readonly .field-label,
  .dynamic-form.readonly .field-value {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  /* Specifieke override voor text-value die anders pre-wrap afdwingt */
  .dynamic-form.readonly .field-value.text-value {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* Boolean icon styling */
.boolean-icon {
    font-size: 20px;
    vertical-align: middle;
}

.boolean-true {
    color: #4caf50; /* Groen voor true */
}

.boolean-false {
    color: #f44336; /* Rood voor false */
}

.field-value.boolean-value {
    display: flex;
    align-items: center;
}

/* Send button styling (ChatInput consistency) */
.send-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    background-color: var(--human-message-background);
    color: var(--human-message-text-color);
    border: 2px solid var(--human-message-text-color);
    border-radius: 50%;
    cursor: pointer;
    transition: background-color 0.2s;
}

.send-btn:hover:not(:disabled) {
    background-color: var(--human-message-background);
}

.send-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

/* Loading spinner for send button */
.loading-spinner {
    display: inline-block;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Flexbox layout for send button mode */
.form-actions.with-send-button {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
</style>