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 { MatSlideToggleModule, MatSlideToggleChange } from '@angular/material/slide-toggle'; // Importa MatSlideToggleChange
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatOptionModule } from '@angular/material/core';// Necessario per il toggle se usato con ngModel
import { ChildService, Child, ChildInput } from '../../services/child.service';
import { Structure, StructureService } from '../../services/structure.service'; // Importa Structure e StructureService
import { ConfirmDialogComponent, ConfirmDialogData } from '../confirm-dialog/confirm-dialog.component';
import { ChildDialogComponent } from '../child-dialog/child-dialog.component'; // Importa il dialog
import { Observable } from 'rxjs';

@Component({
  selector: 'app-children',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatTableModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatDialogModule,
    MatSlideToggleModule,
    DatePipe,
    MatFormFieldModule,
    MatSelectModule,
    MatOptionModule
  ],
  templateUrl: './children.component.html',
  styleUrl: './children.component.scss'
})
export class ChildrenComponent implements OnInit {

  structures: any[] = [];

  children$: Observable<Child[]> | undefined;
  // Colonne per la tabella bambini
  displayedColumns: string[] = [
    'id',
    'last_name',
    'first_name',
    'date_of_birth',
    'structure_name', // Nome struttura associata
    'is_active',
    'actions'
  ];
  isLoading = false;
  error: string | null = null;
  structureIdFilter: number | null = null;
  isActiveFilter: boolean | null = true; // Mostra solo attivi di default

  constructor(
    private childService: ChildService,
    private dialog: MatDialog,
    private structureService: StructureService // Inietta StructureService
  ) { }

  ngOnInit(): void {
    this.loadStructures(); // Carica le strutture
    this.loadChildren(); // Carica i bambini (con filtri)
  }

  // Metodo per caricare le strutture per il filtro
  loadStructures(): void {
    // Non impostiamo isLoading = true qui per non interferire con lo spinner principale
    this.structureService.getStructures().subscribe({
      next: (structures: Structure[]) => { // Specifica il tipo
        this.structures = structures;
      },
      error: (err: any) => { // Specifica il tipo (o un tipo di errore più specifico se noto)
        console.error('Error loading structures for filter:', err);
        // Potresti voler mostrare un errore specifico per il caricamento dei filtri
      }
    });
  }

  loadChildren(): void {
    this.isLoading = true;
    this.error = null;
    // TODO: Aggiungere filtri UI per structure_id e is_active
    const filters: any = {};
    if (this.structureIdFilter !== null && this.structureIdFilter !== undefined) {
      filters.structure_id = this.structureIdFilter;
    }
    if (this.isActiveFilter !== null && this.isActiveFilter !== undefined) {
      filters.is_active = this.isActiveFilter;
    }
    this.children$ = this.childService.getChildren(filters);

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

  addChild(): void {
    const dialogRef = this.dialog.open(ChildDialogComponent, {
      width: '80vw', // Dialog più largo per più campi
      maxWidth: '80vw',
      data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.isLoading = true;
        this.childService.addChild(result).subscribe({
          next: () => this.loadChildren(),
          error: (err) => {
            console.error('Error adding child:', err);
            this.error = err.error?.error || 'Errore durante l\'aggiunta del bambino.';
            this.isLoading = false;
          }
        });
      }
    });
  }

  editChild(child: Child): void {
     // Recupera dati completi prima di aprire
     this.childService.getChild(child.id).subscribe({
        next: (fullChildData) => {
            const dialogRef = this.dialog.open(ChildDialogComponent, {
              width: '80vw',
              maxWidth: '80vw',
              data: { child: fullChildData }
            });

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

  deleteChild(child: Child): void {
    const dialogData: ConfirmDialogData = {
      title: 'Conferma Eliminazione Bambino',
      message: `Sei sicuro di voler eliminare ${child.first_name} ${child.last_name} (ID: ${child.id})?`,
      confirmButtonText: 'Elimina'
    };

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

    dialogRef.afterClosed().subscribe(confirmed => {
      if (confirmed) {
        this.isLoading = true;
        this.childService.deleteChild(child.id).subscribe({
          next: () => this.loadChildren(),
          error: (err) => {
            console.error(`Error deleting child ${child.id}:`, err);
            this.error = 'Errore durante l\'eliminazione del bambino.';
            this.isLoading = false;
          }
        });
      }
    });
  }
   // Gestisce il cambio di stato attivo/inattivo
  toggleActive(child: Child, event: MatSlideToggleChange): void {
    this.isLoading = true;
    this.error = null;
    const updatedChild: ChildInput = { is_active: event.checked };

    this.childService.updateChild(child.id, updatedChild).subscribe({
       next: () => {
           console.log(`Successfully updated active state for ${child.id}`);
           // Potremmo aggiornare solo l'elemento localmente invece di ricaricare tutto
           // Ma per ora ricarichiamo per semplicità
           this.loadChildren();
       },
       error: (err) => {
         console.error(`Error toggling active state for child ${child.id}:`, err);
         this.error = 'Errore durante l\'aggiornamento dello stato.';
         this.isLoading = false;
         this.loadChildren(); // Ricarica per ripristinare
       }
    });
  }

}

