import { Component, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { GetMaxMinStock, UpdateStockMaxMin } from '../../../../interfaces/inventory-management/max-min-stock.interface';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { EncService } from '../../../../services/enc.service';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-form-max-min-stock',
    templateUrl: './form-max-min-stock.component.html',
    styleUrl: './form-max-min-stock.component.css',
    standalone: false
})
export class FormMaxMinStockComponent {
  public isLoading: boolean;
  public formGroup: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) public maxMinStock: GetMaxMinStock,
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _encService: EncService,
  ) {
    this.isLoading = false;
    this.formGroup = this._createFormGroup();
  }

  private _createFormGroup() {
    return new FormGroup({
      'MODELO': new FormControl(this.maxMinStock.MODELO),
      'CODIGO_MODELO': new FormControl(this.maxMinStock.CODIGO_MODELO),
      'STOCK_MINIMO': new FormControl(this.maxMinStock.STOCK_MINIMO === 'Sin Definir' ? null : this.maxMinStock.STOCK_MINIMO, [Validators.required, Validators.min(1)]),
      'STOCK_MAXIMO': new FormControl(this.maxMinStock.STOCK_MAXIMO === 'Sin Definir' ? null : this.maxMinStock.STOCK_MAXIMO, [Validators.required, Validators.min(1)]),
    });
  }

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de modificar el stock mínimo y máximo?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.updateStockMaxMin();
      }
    });
  }

  private async updateStockMaxMin() {
    const encInfo = await this._encService.encrypt(this.maxMinStock.ID_INFORMACION_STOCK.toString());
    const updateStockMaxMin: UpdateStockMaxMin = {
      STOCK_MINIMO: this.formGroup.controls['STOCK_MINIMO'].value,
      STOCK_MAXIMO: this.formGroup.controls['STOCK_MAXIMO'].value,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    await lastValueFrom(this._inventoryManagementService.updateStockMaxMin(encInfo, updateStockMaxMin)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación Existosas!`);
          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.updateStockMaxMin();
        }
      }
    );
  }
}
