import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

export interface FormField {
  name: string;
  label: string;
  type: 'text' | 'email' | 'number' | 'date' | 'select' | 'textarea' | 'checkbox';
  value?: any;
  placeholder?: string;
  required?: boolean;
  options?: { value: any; label: string }[];
  validators?: any[];
  hint?: string;
}

export interface FormDialogData {
  title: string;
  fields: FormField[];
  submitText?: string;
  cancelText?: string;
  width?: string;
}

/**
 * Modal générique de formulaire
 * Remplace: modal-data-export, modal-generate-document, modal-generate-reporting,
 *           modal-add-reporting, modal-execute
 */
@Component({
  selector: 'app-form-dialog',
  templateUrl: './form-dialog.component.html',
  styleUrls: ['./form-dialog.component.scss'],
})
export class FormDialogComponent implements OnInit {
  form!: FormGroup;
  loading = false;

  constructor(
    private fb: FormBuilder,
    public dialogRef: MatDialogRef<FormDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: FormDialogData
  ) {
    // Valeurs par défaut
    this.data.submitText = data.submitText || 'Valider';
    this.data.cancelText = data.cancelText || 'Annuler';
  }

  ngOnInit(): void {
    this.buildForm();
  }

  private buildForm(): void {
    const formConfig: any = {};

    this.data.fields.forEach((field) => {
      const validators = field.required ? [Validators.required, ...(field.validators || [])] : field.validators || [];
      formConfig[field.name] = [field.value || '', validators];
    });

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

  onSubmit(): void {
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }

    this.dialogRef.close(this.form.value);
  }

  onCancel(): void {
    this.dialogRef.close(null);
  }

  getErrorMessage(fieldName: string): string {
    const field = this.form.get(fieldName);
    if (!field || !field.errors) return '';

    if (field.errors['required']) {
      const fieldConfig = this.data.fields.find((f) => f.name === fieldName);
      return `${fieldConfig?.label || 'Ce champ'} est requis`;
    }

    if (field.errors['email']) {
      return 'Email invalide';
    }

    if (field.errors['min']) {
      return `Valeur minimale : ${field.errors['min'].min}`;
    }

    if (field.errors['max']) {
      return `Valeur maximale : ${field.errors['max'].max}`;
    }

    return 'Valeur invalide';
  }
}
