import { HttpErrorResponse } from '@angular/common/http';
import { Component, AfterViewInit, ViewChild, OnInit } 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 { AlertData } from 'src/app/interfaces/alert.interface';
import { DialogModule, ModuloResponse, ResponseData } from 'src/app/interfaces/getb/getbgm.interface';
import { GETBGMService } from 'src/app/services/forms-management/getbgm/getbgm.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ModuleManagementFormComponent } from './module-management-form/module-management-form.component';

@Component({
  selector: 'app-getbgm',
  templateUrl: './module-management.component.html',
  styleUrls: ['./module-management.component.css'],
})
export class ModuleManagementComponent implements AfterViewInit, OnInit {
  public displayedColumns: string[];
  public dataSource: MatTableDataSource<ModuloResponse>;
  public txtBuscador:string;

  public isLoading: boolean = true;
  public isLoadingForm: boolean = false;

  // ---- SmartPage ----
  public btnSmall: boolean = false;

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

  constructor(
    public dialog: MatDialog,
    private _resourceService: ResourcesService,
    private _moduloService: GETBGMService
  ) {
    this.displayedColumns = ['CODIGO_MODULO','MODULO','FECHA_MOD','ESTADO','ACCIONES'];
    this.dataSource = new MatTableDataSource();
    this.txtBuscador = '';
  }

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

  // Método implementado por angular OnInit
  ngOnInit(): void {
    // Se establecen las dimensiones de la pantalla
    this.onResize();
    this.consultarModulos();

  }

  public async consultarModulos() {
    this.isLoading = true;
    await lastValueFrom(this._moduloService.getModules()).then(
      (data: ResponseData) => {
        if (!data.error) this.dataSource.data = data.response;
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async openForm( accion: string, data?: any ) {
    this.isLoadingForm = true;
    this.dialog.open(ModuleManagementFormComponent, {
      width: '500px',
      disableClose: true,
      data: { action: accion, dataElement: data, },
    }).afterClosed().subscribe((result) => {
      if (result === 'EXITO') {
        this.consultarModulos();
      } else if (result === 'CLOSE') {
      }
    });
    this.isLoadingForm = false;
  }

  // Método para ejecutar una alerta
  public async alert(type: string, data: any = null) {
    this.isLoadingForm = true;

    // Se asigna la información de la alerta según el tipo de acción
    let info: AlertData = {} as AlertData;
    if (type === 'ELM') {
      info = {
        icon: "warning",
        title: "Eliminar Módulo",
        description: "¿Está seguro de eliminar este módulo?"
      };
    }

    // Se ejecuta la alerta
    const dialogRef = this.dialog.open(AlertComponent, {
      data: info,
      disableClose: true,
      width: '350px',
    });

    // Se obtiene la respuesta obtenida por la alerta
    dialogRef.afterClosed().subscribe((result) => {
      // Se ejecuta la acción según el tipo seleccionado
      if (result && type === 'ELM') {

        // Se ejecuta el método para eliminar una tabla
        this.deleteModule(data.MODU_IDMO);
      }
      this.isLoadingForm = false;
    });
  }

  // Método para eliminar un registro
  private async deleteModule(codigo: string) {
    await lastValueFrom(
      this._moduloService.deleteModule({ codigo: codigo, user: this._resourceService.getUser() })
    ).then((data: ResponseData) => {
      if (!data.error) {
        this._resourceService.openSnackBar('¡Eliminación exitosa!');
        this.consultarModulos();
      }
    },(error: HttpErrorResponse) =>
        this._resourceService.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;
  }

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