import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { SpecialtiesListItem, SpecialtiesListResponse } from '../../../interfaces/specialties.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { InterventionService } from '../../../services/personal-management/intervention.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { SpecialtyFormComponent } from './specialty-form/specialty-form.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-specialties-management',
    templateUrl: './specialties-management.component.html',
    styleUrl: './specialties-management.component.css',
    standalone: false
})
export class SpecialtiesManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  dataSource: MatTableDataSource<SpecialtiesListItem>;
  displayedColumns = ['CODIGO', 'NOMBRE', 'ESTADO', 'ULMOD', 'ACCIONES'];

  public txtBuscador:string;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    private _interventionService: InterventionService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.dataSource = new MatTableDataSource();

    this.txtBuscador = '';
  }

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

  async getSpecialties(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';

      let idUser = localStorage.getItem('idusuario')!;
      let specialties: SpecialtiesListResponse = await lastValueFrom(this._interventionService.getSpecialties(idUser, 1));

      this.hasError = specialties.error;
      this.errorStr = specialties.msg;

      if(!this.hasError){
        let specialtiesArr: SpecialtiesListItem[] = [];
        for(const specialty of specialties.response){
          console.log(specialty);
          specialty.CODIGO_ESPECIALIDAD = await this._encService.decrypt(specialty.CODIGO_ESPECIALIDAD);
          specialtiesArr.push(specialty);
        }

        this.dataSource = new MatTableDataSource(specialtiesArr);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = 'Ocurrió un error inesperado.';
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  openNewSpecialtyForm(type: string, specialty?: string){
    let dialogRef = this._dialog.open(SpecialtyFormComponent, {
      width: '480px',
      maxWidth: '480px',
      disableClose: true,
      data: {
        type: type,
        specialty: specialty,
      }
    });
    
    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveSpecialty(res, type);
      }
    });
  }

  async saveSpecialty(dataEnc: string, type: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();
      let codeEnc = await this._encService.encrypt(dataObj.code);

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('specialty_code', codeEnc);
      formData.append('spacialty_name', dataObj.name);

      if(type == 'new'){
        await lastValueFrom(this._interventionService.registerSpecialty(formData));
        this._resourcesService.openSnackBar('La especialidad se registró correctamente.');
      }else{
        await lastValueFrom(this._interventionService.updateSpecialty(formData));
        this._resourcesService.openSnackBar('La especialidad se actualizó correctamente.');
      }

      this.getSpecialties();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  openDeleteAlert(specialty: string){
    let specialtyFilt = this.dataSource.data.filter(item => item.CODIGO_ESPECIALIDAD == specialty);
    if(specialtyFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de eliminar la especialidad ${specialtyFilt[0].NOMBRE_ESPECIALIDAD} (${specialty})?`,
          description2: 'Esta acción no se puede deshacer.',
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.deleteSpecialty(specialty);
        } 
      });
    }
  }

  private async deleteSpecialty(code: string){
    try{
      let codeEnc = await this._encService.encrypt(code);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('specialty_code', codeEnc);

      await lastValueFrom(this._interventionService.deleteSpecialty(formData));

      this._resourcesService.openSnackBar('La especialidad se eliminó correctamente.');
      this.getSpecialties();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
