import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DataDialogPaymentMethod, RequestFormPaymentMethod, ResponseDataPaymentMethod } from '../../../../interfaces/budget-management/budget-management.interface';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { BudgetManagementService } from '../../../../services/budget-management/budget-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-form-payment-method',
    templateUrl: './form-payment-method.component.html',
    styleUrl: './form-payment-method.component.css',
    standalone: false
})
export class FormPaymentMethodComponent implements OnInit {
  public type!: 'REG' | 'UPD';
  public title: string;
  public idPayment!: string;
  public formGroup: FormGroup;
  public isLoading: boolean;
  
  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataDialogPaymentMethod,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _encService: EncService,
    private _budgetManagementService: BudgetManagementService,
  ) {
    this.title = '...';
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup(): FormGroup {
    return new FormGroup({
      TIPO_METODO_PAGO: new FormControl(null, Validators.required),
      DESCRIPCION: new FormControl(null),
    });
  }
  
  async ngOnInit() {
    this.isLoading = true;
    this.type = this.dataDialog.TYPE_DIALOG;
    if (this.type === 'REG') {
      this.title = 'Registro de método de pago';
    } else if ( this.type === 'UPD' && this.dataDialog.ID !== undefined) {
      this.title = 'Modificación de método de pago';
      this.idPayment = this.dataDialog.ID;
      await this._getPaymentMethodById();
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      this._dialogRef.close(false);
    }
    this.isLoading = false;
  }

  private async _getPaymentMethodById() {
    const ID_PAYMENT: string = await this._encService.encrypt(this.idPayment);
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();

    await lastValueFrom(this._budgetManagementService.getPaymentMethodById(ID_PAYMENT, USER, LINE)).then(
      (responseData: ResponseDataPaymentMethod) => {
        if (!responseData.error && Object.keys(responseData.response).length > 0) {
          this.formGroup.controls['TIPO_METODO_PAGO'].setValue(responseData.response.TIPO_METODO_PAGO)
          this.formGroup.controls['DESCRIPCION'].setValue(responseData.response.DESCRIPCION)
        } else if (!responseData.error && Object.keys(responseData.response).length === 0) {
          this.resourcesService.openSnackBar(`No se encontró información a mostrar.`);
          this._dialogRef.close(false);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
          this._dialogRef.close(false);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getPaymentMethodById();
        }
        this._dialogRef.close(false);
      }
    );
  }

  public save() {
    if (this.type === 'REG') {
      this._dialog.open(AlertComponent, {
        data: {
          title: `Confirmación`,
          description: `¿Está seguro de registrar el método de pago?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this._registerPaymentMethod();
        }
      });
    } else if (this.type === 'UPD') {
      this._dialog.open(AlertComponent, {
        data: {
          title: `Confirmación`,
          description: `¿Está seguro de modificar el método de pago?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this._updatePaymentMethod();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      this._dialogRef.close(false);
    }
  }

  private async _registerPaymentMethod() {
    this.isLoading = true;
    const DATA_REQUEST = this._dataRequest();
    await lastValueFrom(this._budgetManagementService.registerPaymentMethod(DATA_REQUEST)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Registro exitoso!`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._registerPaymentMethod();
        }
      }
    );
    this.isLoading = false;
  }

  private _dataRequest() : RequestFormPaymentMethod {
    let tipoMetodoPago = this.formGroup.controls['TIPO_METODO_PAGO'].value;
    tipoMetodoPago = tipoMetodoPago.toString().trim();

    let descripcion = this.formGroup.controls['DESCRIPCION'].value;
    descripcion = descripcion.toString().trim();


    const requestForm: RequestFormPaymentMethod = {
      TIPO_METODO_PAGO: tipoMetodoPago,
      DESCRIPCION: descripcion,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    return requestForm;
  }
  
  private async _updatePaymentMethod() {
    this.isLoading = true;
    const DATA_REQUEST: RequestFormPaymentMethod = this._dataRequest();
    const ENC_PAYMENT: string = await this._encService.encrypt(this.idPayment);
    await lastValueFrom(this._budgetManagementService.updatePaymentMethod(DATA_REQUEST, ENC_PAYMENT)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación exitosa!`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._updatePaymentMethod();
        }
      }
    );
    this.isLoading = false;
  }
}
