import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { EncService } from 'src/app/services/enc/enc.service';
import { WorkTeamService } from 'src/app/services/personal-management/work-team.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { WorkTeamFormComponent } from './work-team-form/work-team-form.component';

@Component({
  selector: 'app-work-team',
  templateUrl: './work-team.component.html',
  styleUrls: ['./work-team.component.css']
})
export class WorkTeamComponent implements OnInit {

  public isLoading: boolean;
  public isLoadingForm: boolean;

  public btnSmall: boolean;
  public txtBuscador: string;
  public dataSource: MatTableDataSource<any>;
  public displayedColumns: Array<string>;

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

  constructor(
    public resourcesService: ResourcesService,
    private _workteamService: WorkTeamService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService
  ) {
    this.btnSmall = false;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<any>();
    this.isLoading = true;
    this.isLoadingForm = false;
    this.displayedColumns = [
      'NAME',
      'SPECIALITY',
      'STATUS',
      'ACCIONES']
  }

  ngOnInit(): void {
    this.getWorkteams();
    this.onResize();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  
  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'REG' || typeForm === 'UPD'|| typeForm === 'DET') {
      this._dialog.open(WorkTeamFormComponent, {
        width: '800px',
        disableClose: true,
        data: { action: typeForm, dataElement: element },
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.getWorkteams();
        }
      });
    } else if (typeForm === 'DEL') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Eliminación de Equipo de Trabajo',
          description: '¿Está seguro que desea eliminar al equipo de trabajo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteWorkteam(element!.WORKTEAM_ID);
        }
      });
    }
  }

  private async deleteWorkteam(workteamId: string) {
    let idWorkteamEnc = await this._encService.encrypt(`${workteamId}`);
    console.log(idWorkteamEnc);
    
    await lastValueFrom(this._workteamService.updateToInactiveStatus({
      WORKTEAM_ID: idWorkteamEnc,
      linea: 1,
      id_user: this.resourcesService.getUser()
    })).then(
      (responseData: any) => {
        this.getWorkteams();
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public async getWorkteams() {
    this.isLoading = true;
    
    let idUser = localStorage.getItem('idusuario')!;
    await lastValueFrom(this._workteamService.getConsultOfWorkteams(idUser)).then(
      (responseData: any) => {
        this.dataSource.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    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();
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
