<template>
    <div class="dynamic-form-container">
        <div class="dynamic-form">
            <!-- Form header with icon and title -->
            <div v-if="formData.title || formData.name || formData.icon" 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 -->
            <div 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)"
                    />
                </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)"
                    />
                </template>
            </div>

            <!-- Form actions (only show if not hidden and not read-only) -->
            <div v-if="!hideActions && !readOnly" class="form-actions">
                <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>
            </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'}">
                        {{ formatFieldValue(fieldId, field) }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: 'DynamicForm',
    components: {
        'form-field': FormField
    },
    setup(props) {
        const { watchIcon } = useIconManager();
        
        // Watch formData.icon for automatic icon loading
        watchIcon(() => props.formData?.icon);
        
        return {};
    },
    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
        }
    },
    emits: ['submit', 'cancel', 'update:formValues'],
    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];
                        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];
                        if (value === undefined || value === null || 
                            (typeof value === 'string' && !value.trim()) ||
                            (Array.isArray(value) && value.length === 0)) {
                            missingFields.push(field.name);
                        }
                    }
                });
            }

            return missingFields.length === 0;
        }
    },
    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));
                }
            },
            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
    },
    methods: {
        updateFieldValue(fieldId, value) {
            // Update lokale waarde
            this.localFormValues = {
                ...this.localFormValues,
                [fieldId]: value
            };
        },

        handleSubmit() {
            // 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];
                        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];
                        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');
        },

        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') {
                return value ? 'Ja' : 'Nee';
            } else if (field.type === 'enum' && !value && field.default) {
                return field.default;
            }

            return value.toString();
        }
    }
};
</script>

<style scoped>
/* Dynamisch formulier stijlen */
.dynamic-form-container {
    margin-bottom: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    background-color: #f9f9f9;
}

.dynamic-form {
    padding: 15px;
}

.form-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e0e0e0;
}

.form-icon {
    margin-right: 10px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #555;
}

.form-title {
    font-size: 1.2rem;
    font-weight: 600;
    color: #333;
}

.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;
    color: #555;
}

.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;
    color: #555;
}

.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: 10px;
}

.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: 10px 0;
}

.form-field-readonly {
    display: flex;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
}

.field-label {
    flex: 0 0 30%;
    font-weight: 500;
    color: #555;
    padding-right: 10px;
}

.field-value {
    flex: 1;
    word-break: break-word;
}

.text-value {
    white-space: pre-wrap;
}
</style>