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 { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DispatchFormComponent } from './dispatch-form/dispatch-form.component';
import { DispatchService } from 'src/app/services/acquisition-management/dispatch.service'
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { DispatchData, DispatchForm, DispatchRequest, RequestDeleteDispatch, ResponseDataDispatch } from 'src/app/interfaces/acquisition-management/dispatch.interface';
import { ResponseData } from 'src/app/interfaces/response-data';

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

  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<DispatchData>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public txtBuscador: string;

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

  constructor(
    private _dialog: MatDialog,
    private _dispatchService: DispatchService,
    public resourceService: ResourcesService,
  ) {
    this.displayedColumns = ['NUMERO_DESPACHO', 'DESPACHO', 'DIRECCION', 'FECHA_REGISTRA', 'USUARIO_REGISTRA', 'ESTADO', 'ACCIONES'];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.onResize();
    this.getDistpach();
  }

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

  public async getDistpach() {
    lastValueFrom(this._dispatchService.getDistpach()).then(
      (responseData: ResponseDataDispatch) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );
  }

  // Método para abrir el formulario
  public openDialog(type: string, element: any = null) {
    this._dialog.open(DispatchFormComponent, {
      width: '800px',
      disableClose: true,
      data: {
        typeForm: type,
        dataElement: element,
      }
    }).afterClosed().subscribe((result: any) => {
      if (result) {
        this.getDistpach();
      }
     });
  }

  // Método para ejecutar una alerta
  public async alert(type: string, dataElement: any = null): Promise<void> {
    this.isLoadingForm = true;
    let dataDialog: AlertData = {} as AlertData;

    if (type === 'ELI') {
      dataDialog = {
        icon: "warning",
        title: "Eliminar Despacho",
        description: "¿Está seguro de eliminar el despacho?"
      };
    }

    // Se ejecuta la alerta
    this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
      // width: '500px',
    }).afterClosed().subscribe((result) => {
      if (result && type === 'ELI') {
        this.deleteDispatch(dataElement);
      }
    });
    this.isLoadingForm = false;
  }

  private async deleteDispatch(dataElement:DispatchData) {
    this.isLoadingForm = true;
    const objRequest: RequestDeleteDispatch = {
      NUMERO_DESPACHO: dataElement.DESP_NUDE,
      USUARIO: this.resourceService.getUser(),
      NUMERO_LINEA: '1'
    }
    await lastValueFrom(this._dispatchService.deleteDispatch(objRequest)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourceService.openSnackBar('¡Eliminación del Despacho Exitoso!');
          this.getDistpach();
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

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

  // Método para dar formato a las fechas y horas
  public formatDate(dateRegister: string, dateUpdate: string | null): string {
    let date: string = (dateUpdate === null) ? dateRegister : dateUpdate;
    let arrDateTime: Array<string> = date.split(' ');
    let arrDate: Array<string> = arrDateTime[0].split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  }
}
