import { Component, OnInit } from '@angular/core';
import { CommonModule, DatePipe } from '@angular/common';
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 { TeacherContractService, TeacherContract } from '../../services/teacher-contract.service'; // Importa servizio e interfaccia
import { ConfirmDialogComponent, ConfirmDialogData } from '../confirm-dialog/confirm-dialog.component';
import { TeacherContractDialogComponent } from '../teacher-contract-dialog/teacher-contract-dialog.component'; // Importa il dialog
import { Observable } from 'rxjs';

@Component({
  selector: 'app-contracts',
  standalone: true,
  imports: [
    CommonModule,
    MatTableModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    DatePipe
  ],
  templateUrl: './contracts.component.html',
  styleUrl: './contracts.component.scss'
})
export class ContractsComponent implements OnInit {

  contracts$: Observable<TeacherContract[]> | undefined;
  // Colonne per la tabella contratti (includendo nomi joinati)
  displayedColumns: string[] = [
    'id',
    'teacher_name', // Nome combinato
    'school_year_name',
    'structure_name', // Aggiunto nome struttura
    'contract_type',
    'start_date',
    'end_date',
    'actions'
  ];
  isLoading = false;
  error: string | null = null;

  constructor(
    private teacherContractService: TeacherContractService,
    private dialog: MatDialog
  ) { }

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

  loadContracts(): void {
    this.isLoading = true;
    this.error = null;
    // Passa eventuali filtri se necessario, per ora carica tutto
    this.contracts$ = this.teacherContractService.getTeacherContracts();

    this.contracts$.subscribe({
      next: () => this.isLoading = false,
      error: (err) => {
        console.error('Error loading teacher contracts:', err);
        this.error = 'Errore durante il caricamento dei contratti.';
        this.isLoading = false;
      }
    });
  }

  addContract(): void {
    const dialogRef = this.dialog.open(TeacherContractDialogComponent, {
      width: '600px', // Adatta larghezza
      data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.teacherContractService.addTeacherContract(result).subscribe({
          next: () => this.loadContracts(),
          error: (err) => {
            console.error('Error adding contract:', err);
            // Mostra errore specifico se disponibile (es. duplicate, invalid FK)
            this.error = err.error?.error || 'Errore durante l\'aggiunta del contratto.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  editContract(contract: TeacherContract): void {
     // Recupera i dati completi del contratto prima di aprire il dialog
     // perché la tabella potrebbe mostrare solo dati parziali o formattati
     this.teacherContractService.getTeacherContract(contract.id).subscribe({
        next: (fullContractData) => {
            const dialogRef = this.dialog.open(TeacherContractDialogComponent, {
              width: '600px',
              data: { contract: fullContractData }
            });

            dialogRef.afterClosed().subscribe(result => {
              if (result) {
                this.isLoading = true;
                this.teacherContractService.updateTeacherContract(contract.id, result).subscribe({
                  next: () => this.loadContracts(),
                  error: (err) => {
                    console.error(`Error updating contract ${contract.id}:`, err);
                    this.error = err.error?.error || 'Errore durante la modifica del contratto.';
                    this.isLoading = false;
                  }
                });
              }
            });
        },
        error: (err) => {
             console.error(`Error fetching full contract data for ID ${contract.id}:`, err);
             this.error = 'Errore nel recuperare i dati completi per la modifica.';
        }
     });
  }

  deleteContract(contract: TeacherContract): void {
    const dialogData: ConfirmDialogData = {
      title: 'Conferma Eliminazione Contratto',
      message: `Sei sicuro di voler eliminare il contratto ID ${contract.id} per ${contract.teacher_first_name} ${contract.teacher_last_name} (${contract.school_year_name})?`,
      confirmButtonText: 'Elimina'
    };

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '450px', // Larghezza maggiore per messaggio più lungo
      data: dialogData
    });

    dialogRef.afterClosed().subscribe(confirmed => {
      if (confirmed) {
        this.isLoading = true;
        this.teacherContractService.deleteTeacherContract(contract.id).subscribe({
          next: () => this.loadContracts(),
          error: (err) => {
            console.error(`Error deleting contract ${contract.id}:`, err);
            this.error = 'Errore durante l\'eliminazione del contratto.';
            this.isLoading = false;
          }
        });
      }
    });
  }
}
