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';

const DATA_EXAMPLE: Array<any> = [
  {
    NUMERO_DESPACHO: '0000000001',
    DESPACHO: 'Despacho Oaxaca',
    CALLE: 'Olivo',
    NUMERO_INTERIOR: null,
    NUMERO_EXTERIOR: '27',
    CODIGO_POSTAL: '62554',
    COLONIA: 'Villas del Descanso',
    MUNICIPIO: 'Cuauhtémoc',
    ENTIDAD: 'Ciudad de México',
    FECHA_REGISTRA: '2023-01-18 11:12:15',
    FECHA_MODIFICA: '2023-01-18 11:12:15',
    USUARIO_REGISTRA: 'Jean Jairo Benitez Meza',
    USUARIO_MODIFICA: 'Jean Jairo Benitez Meza',
    ESTADO: 'Activo',
  }
];

@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<any>;
  @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 _resourceService: ResourcesService,
  ) {
    this.displayedColumns = [ 'NUMERO_DESPACHO', 'DESPACHO', 'DIRECCION', 'FECHA_REGISTRA', 'USUARIO_REGISTRA', 'ESTADO', 'ACCIONES' ];
    this.dataSource = new MatTableDataSource(DATA_EXAMPLE);
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.txtBuscador = '';
  }

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

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


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

    });
  }

  // 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
    const dialogRef = this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
      // width: '500px',
    });

    // Se obtiene la respuesta obtenida por la alerta
    dialogRef.afterClosed().subscribe((result) => {
      if (result && type === 'ELI') {
        this._resourceService.openSnackBar('¡Eliminación Exitosa!');
      }
    });
    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]}`;
  }
}
