import { Component, ChangeDetectorRef } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';

@Component({
  selector: 'app-team',
  templateUrl: './team.page.html',
  styleUrls: ['./team.page.scss'],
  standalone: false
})
export class TeamPage {

  technicians: any[] = [];
  loading = true;
  searchEmail = '';
  searching = false;

  constructor(
    private ichambaService: IchambaService,
    private alertService: AlertService,
    private alertCtrl: AlertController,
    private cdr: ChangeDetectorRef,
  ) {}

  ionViewWillEnter() {
    this.loadTechnicians();
  }

  loadTechnicians() {
    this.loading = true;
    this.ichambaService.getTeamTechnicians().subscribe({
      next: data => {
        this.technicians = data;
        this.loading = false;
        this.cdr.detectChanges();
      },
      error: () => {
        this.loading = false;
        this.cdr.detectChanges();
      }
    });
  }

  refresh(event: any) {
    this.ichambaService.getTeamTechnicians().subscribe({
      next: data => {
        this.technicians = data;
        this.cdr.detectChanges();
        event.target.complete();
      },
      error: () => {
        event.target.complete();
      }
    });
  }

  async addTechnician() {
    const email = this.searchEmail.trim();
    if (!email || this.searching) return;
    this.searching = true;
    this.cdr.detectChanges();

    this.ichambaService.findUserByEmail(email).subscribe({
      next: async (user: any) => {
        this.searching = false;
        this.cdr.detectChanges();
        const alert = await this.alertCtrl.create({
          header: 'Confirmar',
          message: ' ',
          buttons: [
            { text: 'Cancelar', role: 'cancel' },
            { text: 'Agregar', handler: () => this.confirmAdd(user.id) }
          ]
        });
        await alert.present();
        alert.querySelector('.alert-message')!.innerHTML = `¿Estás seguro de agregar a <strong>${user.name}</strong> a tu compañía?`;
      },
      error: () => {
        this.searching = false;
        this.alertService.presentToast('No existe ningún usuario asignado a esa cuenta');
        this.cdr.detectChanges();
      }
    });
  }

  confirmAdd(userId: any) {
    this.ichambaService.addTechnicianByUserId(userId).subscribe({
      next: () => {
        this.alertService.presentToast('Técnico agregado exitosamente');
        this.searchEmail = '';
        this.loadTechnicians();
      },
      error: () => {
        this.alertService.presentToast('No se pudo agregar el técnico.');
      }
    });
  }

  async confirmRemove(tech: any) {
    const alert = await this.alertCtrl.create({
      header: 'Eliminar técnico',
      message: ' ',
      buttons: [
        { text: 'Cancelar', role: 'cancel' },
        { text: 'Eliminar', role: 'destructive', handler: () => this.removeTechnician(tech.id) }
      ]
    });
    await alert.present();
    alert.querySelector('.alert-message')!.innerHTML = `¿Estás seguro de eliminar a <strong>${tech.name}</strong> de tu equipo?`;
  }

  removeTechnician(technicianId: any) {
    this.ichambaService.removeTechnician(technicianId).subscribe({
      next: () => {
        this.alertService.presentToast('Técnico eliminado');
        this.loadTechnicians();
      },
      error: () => {
        this.alertService.presentToast('No se pudo eliminar el técnico.');
      }
    });
  }
}
