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 { lastValueFrom } from 'rxjs';
import { UnprogrammedVisit, UnprogrammedVisitsResponse } from 'src/app/interfaces/unprogrammed-visits.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { VisitDetailsComponent } from './visit-details/visit-details.component';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';

interface VisitStatus{
  VALUE: string;
  LABEL: string;
  SELECTED: boolean;
}
const STATUS_ARR: VisitStatus[] = [
  {VALUE: 'P', LABEL: 'Pendiente de autorización', SELECTED: true},
  {VALUE: 'C', LABEL: 'Cancelado', SELECTED: true},
  {VALUE: 'R', LABEL: 'Rechazado', SELECTED: true},
  {VALUE: 'A', LABEL: 'Autorizado', SELECTED: true},
  {VALUE: 'F', LABEL: 'Finalizado', SELECTED: true},
];
@Component({
  selector: 'app-unprogrammed-visits',
  templateUrl: './unprogrammed-visits.component.html',
  styleUrls: ['./unprogrammed-visits.component.css']
})
export class UnprogrammedVisitsComponent implements OnInit {
  public btnSmall: boolean;
  public txtBuscador:string;

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

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

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  statusArr: VisitStatus[];

  constructor(
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _dialog: MatDialog,
    private _router: Router,
    private _snackBar: MatSnackBar,
  ) { 
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.statusArr = STATUS_ARR;
    this.dataSource = new MatTableDataSource();
  }

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

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

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

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

      let idUser = localStorage.getItem('idusuario')!;
      let statusObj: any = {};

      this.statusArr.forEach(item => {
        statusObj[item.VALUE] = item.SELECTED;
      });

      let statusStr = JSON.stringify(statusObj);
      let statusEnc = await this._encService.encrypt(statusStr);
      let visits: UnprogrammedVisitsResponse = await lastValueFrom(this._prevMaintService.getUnprogrammedVisits(
        statusEnc, 
        idUser, 
        1
      ));

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

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(visits.response);
        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;
    }
  }

  getStatusText(status: string): string{
    if(status == 'P'){
      return "Pendiente de autorización";
    }else if(status == 'A'){
      return "Autorizado";
    }else if(status == 'F'){
      return "Finalizado";
    }else if(status == 'R'){
      return "Rechazado";
    }else if(status == 'C'){
      return "Cancelado";
    }
    return "";
  }

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

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

  openCommentsDialog(idVisit: number, action: string){
    let dialogRef = this._dialog.open(CommentsDialog, {
      width: '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.openSnackBar('La visita se actualizó correctamente.');
      this.getUnprogrammedVisits();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    })
  }
}

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