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'; // Rimosso ValidatorFn, AbstractControl, ValidationErrors
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'; // Per le select
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; // Per caricamento select
import { Observable, forkJoin } from 'rxjs'; // Per caricare dati multipli
import { TeacherContract } from '../../services/teacher-contract.service';
import { Teacher, TeacherService } from '../../services/teacher.service';
import { SchoolYear, SchoolYearService } from '../../services/school-year.service';
import { Structure, StructureService } from '../../services/structure.service';

// Validatore custom rimosso, la validazione del range verrà fatta dal backend

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

  // Liste per le select
  teachers: Teacher[] = []; // Array per popolare la select
  schoolYears: SchoolYear[] = []; // Array per popolare la select e cercare la data
  structures$: Observable<Structure[]> | undefined;
  isLoadingSelects = false;

  constructor(
    public dialogRef: MatDialogRef<TeacherContractDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { contract?: TeacherContract },
    private fb: FormBuilder,
    // Iniettiamo i servizi necessari per popolare le select
    private teacherService: TeacherService,
    private schoolYearService: SchoolYearService,
    private structureService: StructureService
  ) {
    this.isEditMode = !!data?.contract;
    this.title = this.isEditMode ? 'Modifica Contratto Insegnante' : 'Aggiungi Nuovo Contratto';

    this.contractForm = this.fb.group({
      teacher_id: [null, Validators.required],
      school_year_id: [null, Validators.required],
      structure_id: [null], // Opzionale
      contract_type: [''],
      start_date: [null, Validators.required],
      end_date: [null], // Opzionale
      weekly_hours: [null, [Validators.min(0), Validators.pattern(/^\d+(\.\d{1,2})?$/)]], // Numero positivo con max 2 decimali
      salary: [null, [Validators.min(0), Validators.pattern(/^\d+(\.\d{1,2})?$/)]],
      notes: ['']
    }); // Rimosso validatore custom dal gruppo
  }

  ngOnInit(): void {
    this.loadSelectData(); // Carica dati per le select

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

      this.contractForm.patchValue({
        ...this.data.contract,
        start_date: startDate,
        end_date: endDate
        // teacher_id, school_year_id, structure_id sono già nel data.contract
      });
    }
  }

  loadSelectData(): void {
    this.isLoadingSelects = true;
    // Usiamo forkJoin per caricare tutti i dati in parallelo
    forkJoin({
      teachers: this.teacherService.getTeachers(),
      schoolYears: this.schoolYearService.getSchoolYears(),
      structures: this.structureService.getStructures()
    }).subscribe({
      next: (data) => {
        this.teachers = data.teachers;
        this.schoolYears = data.schoolYears;
        // Converti structures$ in un array per coerenza, se necessario altrove, o mantieni Observable
        this.structures$ = new Observable(sub => sub.next(data.structures)); // Manteniamo Observable per structures per ora
        this.isLoadingSelects = false;
        this.setupSchoolYearSubscription(); // Attiva la sottoscrizione DOPO aver caricato i dati
      },
      error: (err) => {
        console.error("Error loading select data for contract dialog:", err);
        this.isLoadingSelects = false;
        this.dialogRef.close();
      }
    });
  }

  // Sottoscrive ai cambiamenti dell'anno scolastico selezionato
  setupSchoolYearSubscription(): void {
    const schoolYearControl = this.contractForm.get('school_year_id');
    if (schoolYearControl) {
      schoolYearControl.valueChanges.subscribe(selectedYearId => {
        if (selectedYearId) {
          const selectedYear = this.schoolYears.find(year => year.id === selectedYearId);
          if (selectedYear) {
            // Estrai l'anno dalla data di inizio dell'anno scolastico
            const startYear = new Date(selectedYear.start_date).getFullYear();
            // Trova il primo giorno di settembre
            let firstWorkingDay = new Date(startYear, 8, 1); // Mese 8 = Settembre (0-based)
            // Controlla il giorno della settimana (0=Domenica, 6=Sabato)
            while (firstWorkingDay.getDay() === 0 || firstWorkingDay.getDay() === 6) {
              firstWorkingDay.setDate(firstWorkingDay.getDate() + 1); // Passa al giorno successivo
            }
            // Aggiorna il campo start_date del form
            this.contractForm.patchValue({ start_date: firstWorkingDay });
          }
        } else {
           // Se l'anno viene deselezionato, potresti voler resettare la data inizio
           // this.contractForm.patchValue({ start_date: null });
        }
      });
    }
  }


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

  onSave(): void {
    if (this.contractForm.valid) {
      const formData = { ...this.contractForm.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()}`
      } else if (formData.end_date === null || formData.end_date === '') {
          formData.end_date = null; // Assicura che sia null se vuoto
      }

       // Converte numeri stringa (se presenti) in numeri float
       if (formData.weekly_hours !== null && formData.weekly_hours !== '') {
           formData.weekly_hours = parseFloat(formData.weekly_hours);
       } else {
           formData.weekly_hours = null;
       }
        if (formData.salary !== null && formData.salary !== '') {
           formData.salary = parseFloat(formData.salary);
       } else {
           formData.salary = null;
       }
        // Assicura che i campi opzionali siano effettivamente null se vuoti/non selezionati
        // (il form potrebbe avere '' o undefined, ma vogliamo inviare null)
        const fieldsToNullCheck = ['structure_id', 'end_date', 'weekly_hours', 'salary', 'notes', 'contract_type'];
        fieldsToNullCheck.forEach(field => {
            if (formData[field] === '' || formData[field] === undefined) {
                formData[field] = null;
            }
        });


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