import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from '../../../services/resources.service';
import { BudgetManagementService } from '../../../services/budget-management/budget-management.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { ResponseDataGetPaymentMethod, GetPaymentMethod } from '../../../interfaces/budget-management/budget-management.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { FormPaymentMethodComponent } from './form-payment-method/form-payment-method.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-payment-method-management',
    templateUrl: './payment-method-management.component.html',
    styleUrl: './payment-method-management.component.css',
    standalone: false
})
export class PaymentMethodManagementComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<GetPaymentMethod>;
  public displayedColumns: string[];
  public isLoading: boolean;
  public isLoadingForm: boolean;

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

  constructor(
    public resourcesService: ResourcesService,
    private _budgetManagementService: BudgetManagementService,
    private _dialog: MatDialog,
  ) {
    this.dataSource = new MatTableDataSource<GetPaymentMethod>();
    this.displayedColumns = [
      'ID_METODO_PAGO',
      'TIPO_METODO_PAGO',
      'DESCRIPCION',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ];
    this.isLoading = false;
    this.isLoadingForm = false;
  }
  
  async ngOnInit() {
    await this.getPaymentMethod();
  }

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

  public async getPaymentMethod() {
    this.isLoading = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    
    await lastValueFrom(this._budgetManagementService.getPaymentMethod(USER, LINE)).then(
      (responseData: ResponseDataGetPaymentMethod) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getPaymentMethod();
        }
      }
    );
    this.isLoading = false;
  }

  public async openForm(typeForm: 'REG' | 'UPD', idPayment?: number) {
    if (typeForm === 'REG') {
      this._dialog.open(FormPaymentMethodComponent, {
        data: {
          TYPE_DIALOG: typeForm,
        },
        disableClose: true,
        width: `500px`,
        maxWidth: `500px`,
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.getPaymentMethod();
        }
      });
    } else if (typeForm === 'UPD' && idPayment !== undefined) {
      this._dialog.open(FormPaymentMethodComponent, {
        data: {
          ID: idPayment.toString(),
          TYPE_DIALOG: typeForm,
        },
        disableClose: true,
        width: `500px`,
        maxWidth: `500px`,
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.getPaymentMethod();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
    }
  }

  public delete() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de eliminar el método de pago?`,
        icon: `warning`,
      },
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.getPaymentMethod();
      }
    });
  }
}
