import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { CoinsList, CoinsListResponse } from '../../../../../interfaces/coins-list.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DataInformationArticle, DialogDataFormInformation } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { ResourcesService } from '../../../../../services/resources.service';
import { CataloguesService } from '../../../../../services/catalogues.service';
import { EncService } from '../../../../../services/enc.service';
import { SystemAdminService } from '../../../../../services/system-admin.service';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-artitle-details-form',
    templateUrl: './artitle-details-form.component.html',
    styleUrl: './artitle-details-form.component.css',
    standalone: false
})
export class ArtitleDetailsFormComponent implements OnInit {
  public isLoading: boolean;
  public formGroup: FormGroup;
  public type!: 'R' | 'M';
  public title!: string;


  public filteredOptions?: Observable<string[]>;
  public arrCoins: CoinsList[];
  public catalogCoinsStr: Array<string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dialogDataInformation: DialogDataFormInformation,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _cataloguesService: CataloguesService,
    private _encService: EncService,
    private _systemAdminService: SystemAdminService,
  ) {
    this.formGroup = this.createFormGroup();
    this.isLoading = false;
    this.arrCoins = [];
    this.catalogCoinsStr = [];
  }

  private createFormGroup(){
    return new FormGroup({
      CODIGO : new FormControl( '', [Validators.required, Validators.pattern(/^[^.,\-_:]*$/)]),
      MODELO : new FormControl( '', [Validators.required, Validators.pattern(/^[^.,\-_:]*$/)]),
      MONEDA : new FormControl( '', Validators.required),
      PRECIO : new FormControl( '', Validators.required),
      MONTO_MINIMO : new FormControl( '', Validators.required),
      CARACTERISTICAS : new FormControl( '', Validators.required),
    });
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getCoinsActives();
    this._checkDataDialog();
    this.isLoading = false;

    this.filteredOptions = this.formGroup.controls['MONEDA'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.catalogCoinsStr.filter(option => option.toLowerCase().includes(filterValue));
      }),
    );
  }

  private async getCoinsActives() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._systemAdminService.getCatalogCoins(USER, LINE)).then(
      (responseData: CoinsListResponse) => {
        if (responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existe el catálogo de monedas, favor de ponserse en contacto con el administrador del sistema.`);
          this._dialogRef.close(false);
          return;
        }

        this.arrCoins = responseData.response;
        this.catalogCoinsStr = [];
        for (const element of responseData.response) {
          this.catalogCoinsStr.push(`${element.COIN} (${element.DESCRIPTION})`);
        }
        
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getCoinsActives();
        }
      }
    );
  }

  private _checkDataDialog () {
    this.isLoading = true;

    this.type = this.dialogDataInformation.type;
    if (this.type === 'R') {
      this.title = `Registro de detalles del artículo`;
      
    } else if (this.type === 'M' && this.dialogDataInformation.data !== null) {
      this.title = `Modificación de detalles del artículo`;
      const DATA_INFO: DataInformationArticle = this.dialogDataInformation.data

      this.formGroup.controls['CODIGO'].setValue(DATA_INFO.CODIGO);
      this.formGroup.controls['MODELO'].setValue(DATA_INFO.MODELO);
      this.formGroup.controls['MONEDA'].setValue(DATA_INFO.MONEDA);
      this.formGroup.controls['PRECIO'].setValue(DATA_INFO.PRECIO);
      this.formGroup.controls['MONTO_MINIMO'].setValue(DATA_INFO.MONTO_MINIMO);
      this.formGroup.controls['CARACTERISTICAS'].setValue(DATA_INFO.CARACTERISTICAS);

    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      this._dialogRef.close(false);
    }
    this.isLoading = false;
  }
  

  public save () {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de guardar los detalles de la información?`,
        icon: `warning`,
      },
    }).afterClosed().subscribe(
      (response) => {
        if (response) {
          this.registerInformation();
        }
      }
    );
  }

  public registerInformation () {
    let CODIGO = this.formGroup.controls['CODIGO'].value;
    CODIGO = CODIGO.toString().trim();

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

    let MONEDA = this.formGroup.controls['MONEDA'].value;
    MONEDA = MONEDA.toString().trim();
    MONEDA = MONEDA.split('(')[0].trim();

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

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

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

    const REQUEST_FORM = {
      CODIGO: CODIGO,
      MODELO: MODELO,
      MONEDA: MONEDA,
      PRECIO: PRECIO,
      MONTO_MINIMO: MONTO_MINIMO,
      CARACTERISTICAS: CARACTERISTICAS,
      ESTADO: 'Activo'
    }

    this._dialogRef.close(REQUEST_FORM);
  }
}
