import { Component, Inject, OnInit } 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 { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { Observable } from 'rxjs';
import { Child } from '../../services/child.service'; // Importa interfaccia Child
import { Structure, StructureService } from '../../services/structure.service'; // Per select struttura

@Component({
  selector: 'app-child-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatSelectModule,
    MatCheckboxModule,
    MatProgressSpinnerModule
  ],
  templateUrl: './child-dialog.component.html',
  styleUrl: './child-dialog.component.scss'
})
export class ChildDialogComponent implements OnInit {
  childForm: FormGroup;
  isEditMode: boolean;
  title: string;

  structures$: Observable<Structure[]> | undefined;
  isLoadingSelects = false;

  constructor(
    public dialogRef: MatDialogRef<ChildDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { child?: Child },
    private fb: FormBuilder,
    private structureService: StructureService // Per caricare le strutture
  ) {
    this.isEditMode = !!data?.child;
    this.title = this.isEditMode ? 'Modifica Dati Bambino' : 'Aggiungi Nuovo Bambino';

    this.childForm = this.fb.group({
      first_name: ['', Validators.required],
      last_name: ['', Validators.required],
      date_of_birth: [null, Validators.required],
      enrollment_date: [new Date(), Validators.required], // Default a oggi
      structure_id: [null], // Opzionale
      parent1_name: [''],
      parent1_phone: [''],
      parent1_email: ['', Validators.email],
      parent2_name: [''],
      parent2_phone: [''],
      parent2_email: ['', Validators.email],
      address: [''],
      city: [''],
      notes: [''],
      is_active: [true] // Default a true
    });
  }

  ngOnInit(): void {
    this.loadStructures(); // Carica strutture per la select

    if (this.isEditMode && this.data.child) {
       const dob = this.data.child.date_of_birth ? new Date(this.data.child.date_of_birth) : null;
       const enrollmentDate = this.data.child.enrollment_date ? new Date(this.data.child.enrollment_date) : null;

      this.childForm.patchValue({
        ...this.data.child,
        date_of_birth: dob,
        enrollment_date: enrollmentDate
      });
    }
  }

  loadStructures(): void {
    this.isLoadingSelects = true;
    this.structures$ = this.structureService.getStructures();
    this.structures$.subscribe({
        next: () => this.isLoadingSelects = false,
        error: (err) => {
            console.error("Error loading structures for child dialog:", err);
            this.isLoadingSelects = false;
            // Non chiudiamo il dialog, ma potremmo mostrare un errore
        }
    });
  }

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

  onSave(): void {
    if (this.childForm.valid) {
      const formData = { ...this.childForm.value };

      // Formatta le date
      if (formData.date_of_birth instanceof Date) {
        formData.date_of_birth = `${formData.date_of_birth.getFullYear()}-${(formData.date_of_birth.getMonth()+1).toString().padStart(2, "0")}-${formData.date_of_birth.getDate()}`
      }
      if (formData.enrollment_date instanceof Date) {
        formData.enrollment_date = `${formData.enrollment_date.getFullYear()}-${(formData.enrollment_date.getMonth()+1).toString().padStart(2, "0")}-${formData.enrollment_date.getDate()}`
      }

      // Assicura null per campi opzionali vuoti
       const fieldsToNullCheck = ['structure_id', 'parent1_name', 'parent1_phone', 'parent1_email', 'parent2_name', 'parent2_phone', 'parent2_email', 'address', 'city', 'notes'];
        fieldsToNullCheck.forEach(field => {
            if (formData[field] === '' || formData[field] === undefined) {
                formData[field] = null;
            }
        });


      this.dialogRef.close(formData);
    } else {
       console.log('Child Form Invalid:', this.childForm.errors);
       Object.keys(this.childForm.controls).forEach(key => {
         const control = this.childForm.get(key);
         if (control && control.errors) {
           console.log(`Control Error - ${key}:`, control.errors);
         }
       });
      this.childForm.markAllAsTouched();
    }
  }
}
