import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { Structure } from '../../services/structure.service'; // Importa l'interfaccia

@Component({
  selector: 'app-structure-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule, // Importa ReactiveFormsModule
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule
  ],
  templateUrl: './structure-dialog.component.html',
  styleUrl: './structure-dialog.component.scss'
})
export class StructureDialogComponent {
  structureForm: FormGroup;
  isEditMode: boolean;

  constructor(
    public dialogRef: MatDialogRef<StructureDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { structure?: Structure }, // Dati passati al dialog (opzionale per modifica)
    private fb: FormBuilder
  ) {
    this.isEditMode = !!data?.structure; // Verifica se siamo in modalità modifica

    // Inizializza il form con FormBuilder
    this.structureForm = this.fb.group({
      name: [data?.structure?.name || '', Validators.required], // Campo 'name' obbligatorio
      address: [data?.structure?.address || ''],
      city: [data?.structure?.city || ''],
      province: [data?.structure?.province || ''],
      zip_code: [data?.structure?.zip_code || ''],
      phone: [data?.structure?.phone || ''],
      email: [data?.structure?.email || '', Validators.email], // Validatore email
      notes: [data?.structure?.notes || '']
    });
  }

  onCancel(): void {
    this.dialogRef.close(); // Chiude il dialog senza restituire dati
  }

  onSave(): void {
    if (this.structureForm.valid) {
      // Restituisce i dati del form quando si salva
      this.dialogRef.close(this.structureForm.value);
    } else {
      // Opzionale: marca i campi come toccati per mostrare gli errori
      this.structureForm.markAllAsTouched();
    }
  }
}
