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, ValidatorFn, AbstractControl, ValidationErrors } 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 { MatCheckboxModule } from '@angular/material/checkbox';
import { SchoolYear } from '../../services/school-year.service';

// Validatore custom per assicurare che end_date sia dopo start_date
export const dateRangeValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
  const start = control.get('start_date');
  const end = control.get('end_date');

  // Se entrambe le date sono presenti e valide, confrontale
  if (start?.value && end?.value && start.value instanceof Date && end.value instanceof Date) {
    return start.value < end.value ? null : { dateRange: true }; // Errore se start >= end
  }
  // Se una delle date manca o non è valida, il validatore non si applica (ci pensano i required/datepicker)
  return null;
};


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

  constructor(
    public dialogRef: MatDialogRef<SchoolYearDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { schoolYear?: SchoolYear },
    private fb: FormBuilder
  ) {
    this.isEditMode = !!data?.schoolYear;
    this.title = this.isEditMode ? 'Modifica Anno Scolastico' : 'Aggiungi Nuovo Anno Scolastico';

    this.schoolYearForm = this.fb.group({
      name: ['', Validators.required],
      start_date: [null, Validators.required], // Data inizio obbligatoria
      end_date: [null, Validators.required],   // Data fine obbligatoria
      is_active: [false] // Default a false
    }, { validators: dateRangeValidator }); // Applica il validatore custom al gruppo
  }

  ngOnInit(): void {
    if (this.isEditMode && this.data.schoolYear) {
       const startDate = this.data.schoolYear.start_date ? new Date(this.data.schoolYear.start_date) : null;
       const endDate = this.data.schoolYear.end_date ? new Date(this.data.schoolYear.end_date) : null;

      this.schoolYearForm.patchValue({
        ...this.data.schoolYear,
        start_date: startDate,
        end_date: endDate
      });
    }
  }

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

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

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

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