import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { UnprogrammedVisit, UnprogrammedVisitsResponse } from '../../../interfaces/unprogrammed-visits.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EncService } from '../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { VisitDetailsComponent } from './visit-details/visit-details.component';

@Component({
    selector: 'app-unprogrammed-visits',
    templateUrl: './unprogrammed-visits.component.html',
    styleUrl: './unprogrammed-visits.component.css',
    standalone: false
})
export class UnprogrammedVisitsComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador:string;

  dataSource?: MatTableDataSource<UnprogrammedVisit>;
  displayedColumns = ['ID', 'EQUIP', 'ESTA', 'ACCONES'];

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

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  statusMap: Map<string, string>;

  constructor(
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _dialog: MatDialog,
    private _router: Router,
    private _resourcesService: ResourcesService,
  ) { 
    this.btnSmall = window.innerWidth <= 1530;
    this.txtBuscador = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.dataSource = new MatTableDataSource();

    this.statusMap = new Map();
  }

  ngOnInit(): void {
    this.statusMap.set('P', 'Pendiente de autorización');
    this.statusMap.set('A', 'Autorizado');
    this.statusMap.set('F', 'Finalizado');
    this.statusMap.set('R', 'Rechazado');
    this.statusMap.set('C', 'Cancelado');

    this.getUnprogrammedVisits();
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let visits: UnprogrammedVisitsResponse = await lastValueFrom(this._prevMaintService.getUnprogrammedVisits(
        idUser, 
        1
      ));

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

      if(!this.hasError){
        let visitsArr: UnprogrammedVisit[] = [];
        for(const visit of visits.response){
          visit.IDVISITA = await this._encService.decrypt(visit.IDVISITA);

          let equipmentCodeDec = await this._encService.decrypt(visit.EQUIPAMIENTO);
          visit.TIPO_EQUIPAMIENTO = `${equipmentCodeDec} - ${visit.TIPO_EQUIPAMIENTO}`;

          let equipmentIDDec = await this._encService.decrypt(visit.ID_EQUIPAMIENTO);
          visit.MODELO_EQUIPAMIENTO = `${visit.MODELO_EQUIPAMIENTO} (${equipmentIDDec})`;

          visitsArr.push(visit);
        }
        
        this.dataSource = new MatTableDataSource(visitsArr);
        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.isLoading = false;
      this.hasError = true;
    }
  }

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

  goBack(steps: number){
    window.history.go(steps * -1);
  }

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

  registerVisit(){
    this._router.navigate(['sam/GMPR/AOTR/RVTP/register']); 
  }

  openVisitDetails(id: number){
    this._dialog.open(VisitDetailsComponent, {
      width: '560px',
      maxWidth: '560px',
      data: {
        idVisit: id,
      }
    })
  }

  openCommentsDialog(idVisit: number, action: string){
    let dialogRef = this._dialog.open(CommentsDialog, {
      width: '380px',
      maxWidth: '380px',
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        switch(action){
          case 'auth':
            this.updateVisitStatus(idVisit, res, 'A');
          break;
          case 'end':
            this.updateVisitStatus(idVisit, res, 'F');
          break;
          case 'decline':
            this.updateVisitStatus(idVisit, res, 'R');
          break;
          case 'cancel':
            this.updateVisitStatus(idVisit, res, 'C');
          break;
        }
      }
    });
  }

  async updateVisitStatus(idVisit: number, comments: string, status: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idVisitEnc = await this._encService.encrypt(`${idVisit}`);
      let formData = new FormData();

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_visit', idVisitEnc);
      formData.append('comments', comments);
      formData.append('status', status);

      await lastValueFrom(this._prevMaintService.updateVisitStatus(formData));

      this._resourcesService.openSnackBar('La visita se actualizó correctamente.');
      this.getUnprogrammedVisits();
    }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);
      }
    }
  }
}

@Component({
    selector: 'comments-dialog',
    templateUrl: './comments-dialog.html',
    standalone: false
})
export class CommentsDialog {}
