import { Component, Input, Output, EventEmitter } from '@angular/core';
import { ModalController, IonicModule } from '@ionic/angular';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

export interface FormField {
    type: string;
    key: string;
    name: string;
    required?: boolean;
    options?: { label: string; value: any }[];
    min?: number;
    max?: number;
    pattern?: string;
    placeholder?: string;
    default?: any;
}

@Component({
    selector: 'app-form-collector',
    standalone: true,
    imports: [IonicModule, CommonModule, FormsModule, ReactiveFormsModule],
    templateUrl: './form-collector.component.html',
    styleUrls: ['./form-collector.component.scss'],
})
export class FormCollectorComponent {
    @Input() fieldList: FormField[] = [];
    @Output() formSubmit = new EventEmitter<any>();

    form: FormGroup;
    today = new Date().toISOString();

    constructor(
        private fb: FormBuilder,
        private modalCtrl: ModalController
    ) {
        this.form = this.fb.group({});
    }

    ngOnInit() {
        this.createForm();
    }

    createForm() {
        const group: any = {};

        this.fieldList.forEach(field => {
            const validators = [];
            if (field.required) {
                validators.push(Validators.required);
            }
            if (field.pattern) {
                validators.push(Validators.pattern(field.pattern));
            }
            if (field.min !== undefined) {
                validators.push(Validators.min(field.min));
            }
            if (field.max !== undefined) {
                validators.push(Validators.max(field.max));
            }

            group[field.key] = [null, validators];
        });

        this.form = this.fb.group(group);
    }

    onSubmit() {
        if (this.form.valid) {
            this.formSubmit.emit(this.form.value);
            this.modalCtrl.dismiss(this.form.value);
        } else {
            this.markFormGroupTouched(this.form);
        }
    }

    onCancel() {
        this.modalCtrl.dismiss();
    }

    private markFormGroupTouched(formGroup: FormGroup | FormArray) {
        Object.values(formGroup.controls).forEach(control => {
            control.markAsTouched();

            if (control instanceof FormGroup || control instanceof FormArray) {
                this.markFormGroupTouched(control);
            }
        });
    }

    getFieldControl(key: string): FormControl {
        return this.form.get(key) as FormControl;
    }
}