import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { GetSymptom, ResponseDataGet } from 'src/app/interfaces/ANFA/symptom.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { SymptomService } from 'src/app/services/failure-analysis/symptom.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { SymptomFormComponent } from './symptom-form/symptom-form.component';

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

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;

  public txtBuscador: string;

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

  constructor(
    private _symptomService: SymptomService,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscador = '';

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

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

  public async getSymptoms() {
    this.isLoading = true;
    await lastValueFrom(this._symptomService.getSymptom()).then(
      (responseData: ResponseDataGet) => {
        this.dataSource = new MatTableDataSource<GetSymptom>(responseData.response);
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public openDialog( typeForm: string, element?:GetSymptom ) {
    if ( typeForm === 'REG' || typeForm === 'UPD' ) {
      this._dialog.open( SymptomFormComponent, {
        width: '800px',
        disableClose: true,
        data: { action: typeForm, dataElement: element },
      }).afterClosed().subscribe((result) => {
        if (result === 'EXITO') {
          this.getSymptoms();
        }
      });
    } else if ( typeForm === 'DEL' ) {
      this._dialog.open( AlertComponent, {
        data: {
          title: 'Eliminación de Síntoma',
          description: '¿Está seguro que desea eliminar el síntoma?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteSymptom(element!.NUMERO_SINTOMA);
        }
      });
    }
  }

  private async deleteSymptom(numeroSintoma: string) {
    await lastValueFrom(this._symptomService.deteleProvSymptom({
      NUMERO_SINTOMA: numeroSintoma,
      NUMERO_LINEA: '1',
      USUARIO: this.resourcesService.getUser()
    })).then(
      (responseData: ResponseData) => {
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
      }, (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;
  }

}
