import { HttpErrorResponse } from '@angular/common/http';
import { AfterViewInit, 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 { GetFailure, ResponseDataGet } from 'src/app/interfaces/ANFA/failure.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { FailureService } from 'src/app/services/failure-analysis/failure.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { FailureFormTempComponent } from './failure-form-temp/failure-form-temp.component';

@Component({
  selector: 'app-failure',
  templateUrl: './failure.component.html',
  styleUrls: ['./failure.component.css']
})
export class FailureComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;

  public txtBuscador: string;

  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<GetFailure>;

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

  constructor(
    public resourcesService: ResourcesService,
    private _failureService: FailureService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscador = '';

    this.displayedColumns = ['NUMERO_FALLA','CODIGO_EQUIPAMIENTO','FALLA','CAUSA','CLASIFICACION','FECHA_EMISION',/* 'LIMITE_VALOR', */'USUARIO_REGISTRA','FECHA_REGISTRA','ESTADO','ACCIONES']
    this.dataSource = new MatTableDataSource<GetFailure>();
  }

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

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

  public async getFailures() {
    this.isLoading = true;
    await lastValueFrom(this._failureService.getFailure()).then(
      (responseData: ResponseDataGet) => {
        this.dataSource.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public openDialog( typeForm: string, element?:GetFailure) {
    if ( typeForm === 'REG' || typeForm === 'UPD' ) {
      this._dialog.open( FailureFormTempComponent, {
        width: '800px',
        disableClose: true,
        data: { action: typeForm, dataElement: element },
      }).afterClosed().subscribe((result) => {
        if (result === 'EXITO') {
          this.getFailures();
        }
      });
    } else if ( typeForm === 'DEL' ) {
      this._dialog.open( AlertComponent, {
        data: {
          title: 'Eliminación de la Falla',
          description: '¿Está seguro que desea eliminar la falla?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteFailure(element!.FALL_NUFA);
        }
      });
    }
  }

  public async viewChart(elementData:GetFailure) {
    let dataEquipment = {
      CODIGO_EQUIPAMIENTO: elementData.FALL_COEQ,
      ID_FALLA: elementData.FALL_IDFA,
      FALLA: elementData.LIFA_NOFA
    }
    let strDataEquipment: string = JSON.stringify(dataEquipment);
    let encDataEquipment: string = await this._encService.encriptar(strDataEquipment);
    this._router.navigate(['/sam/ANFA/failure/chart/' + encDataEquipment])
  }

  private async deleteFailure(numeroSintoma: string) {
    await lastValueFrom(this._failureService.deteleFailure({
      NUMERO_FALLA: numeroSintoma,
      NUMERO_LINEA: '1',
      USUARIO: this.resourcesService.getUser()
    })).then(
      (responseData: ResponseData) => {
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
        this.getFailures();
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // 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;
  }


}
