import { 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 { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { GETBGTService } from 'src/app/services/getb/getbgt/getbgt.service';
import { GETBTBService } from 'src/app/services/getb/getbtb/getbtb.service';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { TableDynManagementForm } from './table-dyn-management-form/table-dyn-management-form.component';


@Component({
  selector: 'app-getbtb',
  templateUrl: './table-dyn-management.component.html',
  styleUrls: ['./table-dyn-management.component.css'],
})
export class TableDynManagementComponent implements AfterViewInit, OnInit {
  displayedColumns: string[] = [
    'nombre',
    'modulo',
    'submodulo',
    'menu',
    'estado',
    'acciones',
  ];
  public dataSource: MatTableDataSource<any> = new MatTableDataSource<any>([]);
  public modulos: ModuloResponse[] = [];
  public isLoading: boolean = true;
  public isLoadingForm: boolean = false;

  // ---- SmartPage ----
  public btnSmall: boolean = false;
  public card_size = 'card-size-normal mat-elevation-z8';

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

  constructor(
    public dialog: MatDialog,
    private _getbtbService: GETBTBService,
    private _resourceService: ResourcesService,
    private router: Router
  ) {
    this.dataSource = new MatTableDataSource();
    this.consultarTablasDinamicas();
  }
  ngOnInit(): void {
    this.onResize();
  }

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

  public async consultarTablasDinamicas() {
    this.isLoading = true;
    await lastValueFrom(this._getbtbService.getTableDynamic()).then(
      (data: ResponseData) => {
        if (data.response.length > 0) {
          this.dataSource.data = data.response;
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async registro() {
    this.isLoadingForm = true;

    const dialogRef = this.dialog.open(TableDynManagementForm, {
      data: this.modulos,
      width: '350px',
      disableClose: true,
    });

    this.isLoadingForm = false;

    dialogRef.afterClosed().subscribe(async (result) => {
      if (result) {
      }
    });
  }

  openEdit(idTable: any) {
    this.router.navigate([`/sam/getbtb-edit/${idTable}`]);
  }

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

    const dialogRef = this.dialog.open(AlertComponent, {
      data: info,
      disableClose: true,
      width: '350px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result && type === 'ELM') {
        this.eliminar(data);
      }
      this.isLoadingForm = false;
    });
  }

  public async modificar(codigo_form: string) {
    this.isLoadingForm = true;
    /* await lastValueFrom(this._formService.getFormData(codigo_form)).then(
      (data: ResponseData) => {
        if(!data.error){
          let str_res = JSON.stringify(data.response);
          this._router.navigate(['sam/getbfo-update', { data: str_res }]);
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)

      }
    ); */
    this.isLoadingForm = false;
  }

  public async eliminar(codigo_form: string) {
    /* await lastValueFrom(
      this._formService.deleteForm({ codigo_form: codigo_form })
    ).then(
      (data: ResponseData) => {
        if(!data.error){
          this.dataSource.data = data.response;
        }
      },
      (error: HttpErrorResponse) => this._resourceService.checkErrors(error)
    );
    this.obtener(); */
  }

  public applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  // Método para reajustar la pantalla
  public onResize() {
    if (window.innerWidth <= 1400) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (window.innerWidth > 1400) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
}

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