<h2>Gestione Anni Scolastici</h2>

<div class="actions-header">
  <button mat-raised-button color="primary" (click)="addSchoolYear()">
    <mat-icon>add_circle_outline</mat-icon> Aggiungi Anno Scolastico
  </button>
</div>

<div class="spinner-container" *ngIf="isLoading">
  <mat-spinner diameter="50"></mat-spinner>
</div>

<div *ngIf="error" class="error-message">
  {{ error }}
</div>

<div *ngIf="!isLoading && !error">
  <table mat-table [dataSource]="(schoolYears$ | async) ?? []" class="mat-elevation-z8 school-year-table">

    <!-- Colonna ID -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> ID </th>
      <td mat-cell *matCellDef="let year"> {{year.id}} </td>
    </ng-container>

    <!-- Colonna Nome -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Nome Anno </th>
      <td mat-cell *matCellDef="let year"> {{year.name}} </td>
    </ng-container>

    <!-- Colonna Data Inizio -->
    <ng-container matColumnDef="start_date">
      <th mat-header-cell *matHeaderCellDef> Data Inizio </th>
      <td mat-cell *matCellDef="let year"> {{year.start_date | date:'dd/MM/yyyy'}} </td>
    </ng-container>

    <!-- Colonna Data Fine -->
    <ng-container matColumnDef="end_date">
      <th mat-header-cell *matHeaderCellDef> Data Fine </th>
      <td mat-cell *matCellDef="let year"> {{year.end_date | date:'dd/MM/yyyy'}} </td>
    </ng-container>

    <!-- Colonna Attivo -->
    <ng-container matColumnDef="is_active">
      <th mat-header-cell *matHeaderCellDef> Attivo </th>
      <td mat-cell *matCellDef="let year">
         <mat-slide-toggle
            [checked]="!!year.is_active"
            (change)="toggleActive(year, $event)"
            aria-label="Stato attivo anno scolastico">
         </mat-slide-toggle>
      </td>
    </ng-container>

    <!-- Colonna Azioni -->
    <ng-container matColumnDef="actions">
      <th mat-header-cell *matHeaderCellDef> Azioni </th>
      <td mat-cell *matCellDef="let year">
        <button mat-icon-button color="primary" aria-label="Modifica anno scolastico" (click)="editSchoolYear(year)">
          <mat-icon>edit</mat-icon>
        </button>
        <button mat-icon-button color="warn" aria-label="Elimina anno scolastico" (click)="deleteSchoolYear(year)">
          <mat-icon>delete</mat-icon>
        </button>
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

    <!-- Riga da mostrare quando non ci sono dati -->
    <tr class="mat-row" *matNoDataRow>
        <td class="mat-cell" [attr.colspan]="displayedColumns.length">
            Nessun anno scolastico trovato.
        </td>
    </tr>

  </table>
</div>
