import { Component, Inject, OnInit } from '@angular/core'; // Rimuovi ChangeDetectorRef, OnDestroy
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'; // Per date
import { MatNativeDateModule } from '@angular/material/core'; // Necessario per MatDatepicker
import { MatCheckboxModule } from '@angular/material/checkbox';
import { Teacher } from '../../services/teacher.service'; // Importa l'interfaccia
// import { Subscription } from 'rxjs'; // Rimuovi Subscription

@Component({
  selector: 'app-teacher-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatDatepickerModule,
    MatNativeDateModule, // Importa MatNativeDateModule
    MatCheckboxModule
  ],
  templateUrl: './teacher-dialog.component.html',
  styleUrl: './teacher-dialog.component.scss',
})
export class TeacherDialogComponent implements OnInit { // Rimuovi OnDestroy
  teacherForm: FormGroup;
  isEditMode: boolean;
  title: string;
  // private subscriptions = new Subscription(); // Rimuovi subscriptions

  constructor(
    public dialogRef: MatDialogRef<TeacherDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { teacher?: Teacher },
    private fb: FormBuilder,
    // private cdr: ChangeDetectorRef // Rimuovi cdr
  ) {
    this.isEditMode = !!data?.teacher;
    this.title = this.isEditMode ? 'Modifica Insegnante' : 'Aggiungi Nuovo Insegnante';

    // Inizializza il form
    this.teacherForm = this.fb.group({
      first_name: ['', Validators.required],
      last_name: ['', Validators.required],
      email: ['', [Validators.email]], // Ripristinato validatore email
      phone: [''],
      date_of_birth: [null], // Inizializza a null per il datepicker
      hire_date: [null],
      qualifications: [''],
      is_active: [true] // Default a true per nuovi insegnanti
    });
  }

  ngOnInit(): void {
    // Se siamo in modalità modifica, popola il form con i dati esistenti
    if (this.isEditMode && this.data.teacher) {
       // Converte le date stringa in oggetti Date se necessario per il datepicker
       const dob = this.data.teacher.date_of_birth ? new Date(this.data.teacher.date_of_birth) : null;
       const hireDate = this.data.teacher.hire_date ? new Date(this.data.teacher.hire_date) : null;

      this.teacherForm.patchValue({
        ...this.data.teacher,
        date_of_birth: dob,
        hire_date: hireDate
      });

    } // Fine if (this.isEditMode...)
  }


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

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

      // Formatta le date prima di inviarle (es. YYYY-MM-DD) se necessario
      // Il backend si aspetta un formato DATE SQL standard
      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.hire_date instanceof Date) {
        formData.hire_date = `${formData.hire_date.getFullYear()}-${(formData.hire_date.getMonth()+1).toString().padStart(2, "0")}-${formData.hire_date.getDate()}`
      }

      this.dialogRef.close(formData);
    } else {
      console.log('--- Form Debug ---');
      console.log('Form Status:', this.teacherForm.status);
      console.log('Form Valid:', this.teacherForm.valid);
      console.log('Form Errors:', this.teacherForm.errors);
      console.log('--- Control Details ---');
      Object.keys(this.teacherForm.controls).forEach(key => {
        const control = this.teacherForm.get(key);
        if (control) {
          console.log(`Control: ${key}, Status: ${control.status}, Valid: ${control.valid}, Value:`, control.value, 'Errors:', control.errors);
        }
      });
      this.teacherForm.markAllAsTouched();
    }
  }

  // ngOnDestroy(): void { // Rimuovi ngOnDestroy
  //   this.subscriptions.unsubscribe();
  // }
}
