import { AfterContentInit, AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { lastValueFrom } from 'rxjs';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { MatTableDataSource } from '@angular/material/table';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { GETBFOService } from 'src/app/services/getb/getbfo/getbfo.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { MatSort } from '@angular/material/sort';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-form-dynamic-management',
  templateUrl: './form-dyn-management.component.html',
  styleUrls: ['./form-dyn-management.component.css'],
})
export class FormDynManagementComponent implements AfterViewInit, OnInit {
  public displayedColumns: string[];
  public dataSource: MatTableDataSource<any>
  public modulos: ModuloResponse[] = [];
  public isLoading: boolean = true;
  public isLoadingForm: boolean = false;

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

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public txtBuscador: string;

  constructor(
    public dialog: MatDialog,
    private _router: Router,
    private _formService: GETBFOService,
    private _resourcesService: ResourcesService
  ) {
    this.displayedColumns = [ 'CODIGO_FORM', 'NOMBRE_FORM', 'MODULO', 'FECHA_REG', 'ESTADO', 'ACCIONES' ]
    this.dataSource = new MatTableDataSource<any>();
    this.txtBuscador = '';
    this.btnSmall = false;
  }

  // Método implementado por angular OnInit
  ngOnInit(): void {
    this.onResize();
    this.obtenerFormularios();
  }

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

  public async obtenerFormularios() {
    this.isLoading = true;
    await lastValueFrom(this._formService.getForm()).then(
      (data: ResponseData) => {
        this.dataSource.data = !data.error ? data.response : [];
      },(error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async alert(type: string, data: any = null) {
    this.isLoadingForm = true;
    let info: AlertData = {} as AlertData;
    switch (type) {
      case 'ELM':
        info = {
          icon: "warning",
          title: "Eliminar Formulario",
          description: "¿Está seguro de eliminar este formulario?"
        };
        break;
    }

    const dialogRef = this.dialog.open(AlertComponent, {
      data: info,
      disableClose: true,
      width: '350px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        switch (type) {
          case 'ELM':
            this.eliminar(data);
            break;
        }
      }
      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;
  }

  public async modificar(codigo_form: number) {
    this.isLoadingForm = true;
    await lastValueFrom(this._formService.getFormData(codigo_form)).then(
      (data: ResponseData) => {
        let str_res = JSON.stringify(data.response);
        this._router.navigate([`sam/getbfo-update/${codigo_form}`]);
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  public async eliminar(codigo_form: string) {
    await lastValueFrom(
      this._formService.deleteForm({ CODIGO_FORM: codigo_form, USER: this._resourcesService.getUser() })
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._resourcesService.openSnackBar('¡Eliminación correcta!');
          this.obtenerFormularios();
        }
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

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

  goBack(steps: number){
    window.history.go(steps * -1);
  }
}

export interface ResponseData {
  error: boolean;
  msg: string;
  response: Array<any> | any;
}
export interface ModuloResponse {
  MODULO_CODIGO: string;
  MODULO: string;
  ESTADO: string;
}
