import { HttpErrorResponse } from '@angular/common/http';
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 { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { RequestFormLevel, ResponseDataLevelAreaWarehouse } from 'src/app/interfaces/inventory-management/warehouse-management.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { WarehouseService } from 'src/app/services/inventory-management/warehouse.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-level-form',
  templateUrl: './level-form.component.html',
  styleUrls: ['./level-form.component.css']
})
export class LevelFormComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public titleDialog: string;
  public formGroup: FormGroup;
  public typeDialog!: 'REG' | 'UPD';

  public idWarehouse!: string;
  public idArea!: string;
  public idLevel!: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataFormArea: DataFormLevel,
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _warehouseService: WarehouseService,
    private _dialog: MatDialog,
    private _dialogReg: MatDialogRef<boolean>,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.formGroup = this.createFormGroup();
    this.titleDialog = '';
  }
  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.getDataForm();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  
  private createFormGroup(): FormGroup {
    return new FormGroup({
      CODIGO_NIVEL: new FormControl('', Validators.required),
      NOMBRE_NIVEL: new FormControl('', Validators.required),
      COMENTARIOS: new FormControl(''),
    });
  }

  private async getDataForm() {
    this.typeDialog = this.dataFormArea.typeForm;
    this.idWarehouse = this.dataFormArea.idWarehouse;
    this.idArea = this.dataFormArea.idArea;
    if (this.typeDialog === 'REG') {
      this.titleDialog = `Registro de Nivel`;
    } else if (this.typeDialog === 'UPD' && this.dataFormArea.idLevel !== null) {
      this.titleDialog = `Modificación del Nivel`;
      this.idLevel = this.dataFormArea.idLevel;
      await this.getLevelById();
    } else {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener los datos del formulario.`);
      this._dialogReg.close(false);
    }
  }

  private async getLevelById() {
    const encLevel: string = await this._encService.encrypt(this.idLevel);
    await lastValueFrom(this._warehouseService.getLevelById(encLevel)).then(
      (responseData: ResponseDataLevelAreaWarehouse) => {
        if (!responseData.error && Object.keys(responseData.response).length > 0) {

          let nombreNivel = responseData.response.NOMBRE_NIVEL;
          let comentarios = responseData.response.COMENTARIOS;

          this.formGroup.controls['CODIGO_NIVEL'].setValue(this.idLevel);
          this.formGroup.controls['CODIGO_NIVEL'].disable();
          this.formGroup.controls['NOMBRE_NIVEL'].setValue(nombreNivel);
          this.formGroup.controls['COMENTARIOS'].setValue(comentarios);
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  public save() {
    if (this.typeDialog === 'REG') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          title: `Confirmación de Registro`,
          description: `¿Está seguro de registrar el nivel?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.registerLevel();
        }
      });
    } else if (this.typeDialog === 'UPD') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          title: `Confirmación de la Modificación`,
          description: `¿Está seguro de modificar el nivel?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.updateLevel();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }
  }

  private async registerLevel() {
    const requestFormArea: RequestFormLevel = this.createRequestForm();
    await lastValueFrom(this._warehouseService.registerLevel(requestFormArea)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Registro Exitoso!`);
          this._dialogReg.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }
  private async updateLevel() {
    const requestFormArea: RequestFormLevel = this.createRequestForm();
    const encLevel: string = await this._encService.encrypt(this.idLevel);
    await lastValueFrom(this._warehouseService.updateLevel(requestFormArea, encLevel)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificacióon Exitosa!`);
          this._dialogReg.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  private createRequestForm(): RequestFormLevel {

    let codigoNivel = null;
    if (this.typeDialog === 'REG') {
      codigoNivel = this.formGroup.controls['CODIGO_NIVEL'].value;
    }

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

    let comentarios = this.formGroup.controls['COMENTARIOS'].value;
    if (comentarios === '' || comentarios === undefined) {
      comentarios = null;
    }

    const requestFormLevel: RequestFormLevel = {
      CODIGO_ALMACEN: this.idWarehouse,
      CODIGO_AREA: this.idArea,
      CODIGO_NIVEL: codigoNivel,
      NOMBRE_NIVEL: nombreNivel,
      COMENTARIOS: comentarios,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }

    return requestFormLevel;
  }
}


export interface DataFormLevel {
  typeForm: 'REG' | 'UPD',
  idWarehouse: string;
  idArea: string;
  idLevel: string | null;
}