import { Component, OnInit } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common'; // Importa DatePipe
import { MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatSlideToggleModule, MatSlideToggleChange } from '@angular/material/slide-toggle'; // Importa MatSlideToggleChange
import { FormsModule } from '@angular/forms';
import { SchoolYearService, SchoolYear, SchoolYearInput } from '../../services/school-year.service';
import { ConfirmDialogComponent, ConfirmDialogData } from '../confirm-dialog/confirm-dialog.component';
import { SchoolYearDialogComponent } from '../school-year-dialog/school-year-dialog.component'; // Importa il dialog
// import { SchoolYearDialogComponent } from '../school-year-dialog/school-year-dialog.component';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-school-years',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatTableModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    MatSlideToggleModule,
    DatePipe // Aggiungi DatePipe agli imports
  ],
  templateUrl: './school-years.component.html',
  styleUrl: './school-years.component.scss'
})
export class SchoolYearsComponent implements OnInit {

  schoolYears$: Observable<SchoolYear[]> | undefined;
  displayedColumns: string[] = ['id', 'name', 'start_date', 'end_date', 'is_active', 'actions'];
  isLoading = false;
  error: string | null = null;

  constructor(
    private schoolYearService: SchoolYearService,
    private dialog: MatDialog
  ) { }

  ngOnInit(): void {
    this.loadSchoolYears();
  }

  loadSchoolYears(): void {
    this.isLoading = true;
    this.error = null;
    this.schoolYears$ = this.schoolYearService.getSchoolYears();

    this.schoolYears$.subscribe({
      next: () => this.isLoading = false,
      error: (err) => {
        console.error('Error loading school years:', err);
        this.error = 'Errore durante il caricamento degli anni scolastici.';
        this.isLoading = false;
      }
    });
  }

  addSchoolYear(): void {
    const dialogRef = this.dialog.open(SchoolYearDialogComponent, {
      width: '500px', // Adatta larghezza se necessario
      data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.schoolYearService.addSchoolYear(result).subscribe({
          next: () => this.loadSchoolYears(),
          error: (err) => {
            console.error('Error adding school year:', err);
            this.error = 'Errore durante l\'aggiunta dell\'anno scolastico.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  editSchoolYear(schoolYear: SchoolYear): void {
     // Non serve recuperare dati completi qui, la tabella li ha già
     const dialogRef = this.dialog.open(SchoolYearDialogComponent, {
      width: '500px',
      data: { schoolYear: schoolYear }
    });

     dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.schoolYearService.updateSchoolYear(schoolYear.id, result).subscribe({
          next: () => this.loadSchoolYears(),
          error: (err) => {
            console.error(`Error updating school year ${schoolYear.id}:`, err);
            this.error = 'Errore durante la modifica dell\'anno scolastico.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  deleteSchoolYear(schoolYear: SchoolYear): void {
    const dialogData: ConfirmDialogData = {
      title: 'Conferma Eliminazione Anno Scolastico',
      message: `Sei sicuro di voler eliminare l'anno scolastico "${schoolYear.name}" (ID: ${schoolYear.id})? Potrebbe avere contratti associati.`, // Aggiungere avviso
      confirmButtonText: 'Elimina'
    };

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '400px',
      data: dialogData
    });

    dialogRef.afterClosed().subscribe(confirmed => {
      if (confirmed) {
        this.isLoading = true;
        this.schoolYearService.deleteSchoolYear(schoolYear.id).subscribe({
          next: () => this.loadSchoolYears(),
          error: (err) => {
            console.error(`Error deleting school year ${schoolYear.id}:`, err);
             // Gestire errore specifico (es. 409 Conflict se ci sono contratti)
            this.error = 'Errore durante l\'eliminazione dell\'anno scolastico. Potrebbe essere in uso.';
            this.isLoading = false;
          }
        });
      }
    });
  }

   // Gestisce il cambio di stato attivo/inattivo
  toggleActive(schoolYear: SchoolYear, event: MatSlideToggleChange): void {
    // Aggiorna lo stato localmente per un feedback immediato (ottimistico)
    // Nota: questo potrebbe non riflettere lo stato reale se altri anni vengono disattivati dal backend
    // Ricaricare la lista dopo il successo è più sicuro per la coerenza.
    // schoolYear.is_active = event.checked; // <- Rimosso aggiornamento ottimistico

    this.isLoading = true;
    this.error = null; // Resetta errore precedente
    const updatedSchoolYear: SchoolYearInput = { is_active: event.checked };

    this.schoolYearService.updateSchoolYear(schoolYear.id, updatedSchoolYear).subscribe({
       next: () => {
           console.log(`Successfully updated active state for ${schoolYear.id}`);
           this.loadSchoolYears(); // Ricarica l'intera lista per riflettere tutti i cambiamenti (incluso disattivare altri)
       },
       error: (err) => {
         console.error(`Error toggling active state for school year ${schoolYear.id}:`, err);
         this.error = 'Errore durante l\'aggiornamento dello stato.';
         this.isLoading = false;
         // Ricarica comunque per ripristinare lo stato visivo precedente in caso di errore
         this.loadSchoolYears();
       }
    });
  }

}
