import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { WorkGroupsListItem, WorkGroupsListResponse } from '../../../interfaces/corrective-maintenance.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { EncService } from '../../../services/enc.service';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { FunctionsService } from '../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { WorkGroupFormComponent } from './work-group-form/work-group-form.component';
import { WorkGroupDetailsComponent } from './work-group-details/work-group-details.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-work-groups',
    templateUrl: './work-groups.component.html',
    styleUrl: './work-groups.component.css',
    standalone: false
})
export class WorkGroupsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  screenSize: number;

  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource: MatTableDataSource<WorkGroupsListItem>;
  displayedColumns = ['ID', 'NOMBRE', 'ESPECIALIDAD', 'ESTADO', 'USUARIO', 'FECHA', 'ACCIONES'];

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

  constructor(
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.screenSize = window.innerWidth;
    
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';

    this.dataSource = new MatTableDataSource();
  }

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

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

      let idUser = localStorage.getItem('idusuario')!;
      let workGroups: WorkGroupsListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkGroups(idUser, 1));

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

      if(!this.hasError){
        let workGroupsArr: WorkGroupsListItem[] = [];
        for(const workGroup of workGroups.response){
          let idGroupDec = await this._encService.decrypt(workGroup.ID_GRUPO);
          workGroup.ID_GRUPO = idGroupDec;
          workGroup.FECREG = this._functionsService.orderDate(workGroup.FECREG);

          if(workGroup.FECMOD != null){
            workGroup.FECMOD = this._functionsService.orderDate(workGroup.FECMOD);
          }

          workGroupsArr.push(workGroup);
        }

        this.dataSource = new MatTableDataSource(workGroupsArr);
        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 = error.error.msg;
      }

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

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
    this.screenSize = window.innerWidth;
  }

  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();
    }
  }

  async openWorkGroupForm(action: string, idWorkGroup: string | null){
    let idWorkGroupEnc: string | null = null;
    if(idWorkGroup != null){
      idWorkGroupEnc = await this._encService.encrypt(idWorkGroup);
    }
    
    let dialogRef = this._dialog.open(WorkGroupFormComponent, {
      width: '480px',
      maxWidth: '480px',
      disableClose: true,
      data: {
        action: action,
        idWorkGroup: idWorkGroupEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveWorkGroup(action, res);
      }
    });
  }

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

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('work_group_name', dataObj.workGroupName);
      formData.append('related_teams', JSON.stringify(dataObj.relatedTeams));
      formData.append('specialty', dataObj.specialty);

      if(action == 'new'){
        await lastValueFrom(this._correctiveMaintenanceService.createWorkGroup(formData));
        this._resourcesService.openSnackBar('El grupo de trabajo se registró correctamente.');
      }else{
        let idWorkGroupEnc = await this._encService.encrypt(dataObj.idWorkGroup);
        formData.append('id_work_group', idWorkGroupEnc);

        await lastValueFrom(this._correctiveMaintenanceService.updateWorkGroup(formData));
        this._resourcesService.openSnackBar('El grupo de trabajo se actualizó correctamente.');
      }

      this.getWorkGroups();
    }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);
      }
    }
  }

  async openWorkGroupDetails(idGroup: string){
    let idGroupEnc = await this._encService.encrypt(idGroup);
    this._dialog.open(WorkGroupDetailsComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        idGroup: idGroupEnc
      }
    });
  }

  openConfirmDialog(idWorkGroup: string){
    let woroGroupFilt = this.dataSource.data.filter(group => group.ID_GRUPO == idWorkGroup);
    if(woroGroupFilt.length > 0){
      let workGroup = woroGroupFilt[0];
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: '¡Confirmación!',
          icon: 'warning',
          description: `¿Está seguro de eliminar el grupo de trabajo ${workGroup.NOMBRE_GRUPO} (${workGroup.ID_GRUPO})?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });
      
      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteWorkGroup(idWorkGroup);
        }
      });
    }
  }

  async deleteWorkGroup(idGroup: string){
    try{
      let idGroupEnc = await this._encService.encrypt(idGroup);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_work_group', idGroupEnc);

      await lastValueFrom(this._correctiveMaintenanceService.deleteWorkGroup(formData));

      this._resourcesService.openSnackBar('El grupo de trabajo se eliminó correctamente.');
      this.getWorkGroups();
    }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);
      }
    }
  }
}
