import { Component, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { GetDueDateStock, UpdateDueDateStock } from '../../../../interfaces/inventory-management/due-date-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-due-date',
    templateUrl: './form-due-date.component.html',
    styleUrl: './form-due-date.component.css',
    standalone: false
})
export class FormDueDateComponent {
  public isLoading: boolean;
  public formGroup: FormGroup;

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

  private _createFormGroup() {
    let dueDate: Date | null = null;
    if (this.dueDateStock.FECHA_VENCIMIENTO !== 'Ninguno') {
      dueDate = this.resourcesService.formatStrDateToDate(this.dueDateStock.FECHA_VENCIMIENTO);
    }

    return new FormGroup({
      'FECHA_VENCIMIENTO': new FormControl(dueDate, [Validators.required])
    });
  }

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de modificar la fecha de vencimiento?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.updateStockBarcode();
      }
    });
  }

  public async updateStockBarcode() {
    const encStock = await this._encService.encrypt(this.dueDateStock.ID_STOCK);
    const dueDate = this.formGroup.controls['FECHA_VENCIMIENTO'].value;
    const strDueDate: string = this.resourcesService.getDateFormatCalendar(dueDate);

    const updateDueDateStock: UpdateDueDateStock = {
      FECHA_VENCIMIENTO: strDueDate,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    await lastValueFrom(this._inventoryManagementService.updateDueDateStock(encStock, updateDueDateStock)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación Existosa!`);
          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.updateStockBarcode();
        }
      }
    );
  }
}
