import { Component, OnInit } from '@angular/core';
import { CommonModule } 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 { ShiftDefinitionService, ShiftDefinition } from '../../services/shift-definition.service';
import { ConfirmDialogComponent, ConfirmDialogData } from '../confirm-dialog/confirm-dialog.component';
import { ShiftDefinitionDialogComponent } from '../shift-definition-dialog/shift-definition-dialog.component'; // Importa il dialog
import { Observable } from 'rxjs';

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

  shifts$: Observable<ShiftDefinition[]> | undefined;
  displayedColumns: string[] = ['id', 'name', 'start_time', 'end_time', 'actions'];
  isLoading = false;
  error: string | null = null;

  constructor(
    private shiftDefinitionService: ShiftDefinitionService,
    private dialog: MatDialog
  ) { }

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

  loadShiftDefinitions(): void {
    this.isLoading = true;
    this.error = null;
    this.shifts$ = this.shiftDefinitionService.getShiftDefinitions();

    this.shifts$.subscribe({
      next: () => this.isLoading = false,
      error: (err) => {
        console.error('Error loading shift definitions:', err);
        this.error = 'Errore durante il caricamento delle definizioni turno.';
        this.isLoading = false;
      }
    });
  }

  addShiftDefinition(): void {
    const dialogRef = this.dialog.open(ShiftDefinitionDialogComponent, {
      width: '450px', // Adatta larghezza
      data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.shiftDefinitionService.addShiftDefinition(result).subscribe({
          next: () => this.loadShiftDefinitions(),
          error: (err) => {
            console.error('Error adding shift definition:', err);
            this.error = err.error?.error || 'Errore durante l\'aggiunta della definizione turno.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  editShiftDefinition(shift: ShiftDefinition): void {
     const dialogRef = this.dialog.open(ShiftDefinitionDialogComponent, {
      width: '450px',
      data: { shift: shift } // Passa la definizione esistente
    });

     dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.shiftDefinitionService.updateShiftDefinition(shift.id, result).subscribe({
          next: () => this.loadShiftDefinitions(),
          error: (err) => {
            console.error(`Error updating shift definition ${shift.id}:`, err);
            this.error = err.error?.error || 'Errore durante la modifica della definizione turno.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  deleteShiftDefinition(shift: ShiftDefinition): void {
    const dialogData: ConfirmDialogData = {
      title: 'Conferma Eliminazione Definizione Turno',
      message: `Sei sicuro di voler eliminare la definizione turno "${shift.name}" (ID: ${shift.id})?`,
      confirmButtonText: 'Elimina'
    };

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

    dialogRef.afterClosed().subscribe(confirmed => {
      if (confirmed) {
        this.isLoading = true;
        this.shiftDefinitionService.deleteShiftDefinition(shift.id).subscribe({
          next: () => this.loadShiftDefinitions(),
          error: (err) => {
            console.error(`Error deleting shift definition ${shift.id}:`, err);
            this.error = 'Errore durante l\'eliminazione della definizione turno.';
            this.isLoading = false;
          }
        });
      }
    });
  }
}
