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 { RequestFormZone, ResponseDataZoneLevelAreaWarehouse } 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-zone-form',
  templateUrl: './zone-form.component.html',
  styleUrls: ['./zone-form.component.css']
})
export class ZoneFormComponent implements OnInit{

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public typeDialog!: 'REG'|'UPD';
  public titleDialog!: string;

  public formGroup: FormGroup;

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

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataFormArea: DataFormZone,
    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();
  }
  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.getDataForm();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  private createFormGroup() {
    return new FormGroup({
      'CODIGO_ZONA': new FormControl('', Validators.required),
      'NOMBRE_ZONA': 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;
    this.idLevel = this.dataFormArea.idLevel;
    if (this.typeDialog === 'REG') {
      this.titleDialog = `Registro de Nivel`;
    } else if (this.typeDialog === 'UPD' && this.dataFormArea.idZone !== null) {
      this.titleDialog = `Modificación del Nivel`;
      this.idZone = this.dataFormArea.idZone;
      await this.getZoneById();
    } else {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener los datos del formulario.`);
      this._dialogReg.close(false);
    }
  }

  public async getZoneById() {
    const encZone: string = await this._encService.encrypt(this.idZone);
    await lastValueFrom(this._warehouseService.getZoneById(encZone)).then(
      (responseData: ResponseDataZoneLevelAreaWarehouse) => {
        if (!responseData.error && Object.keys(responseData.response).length > 0) {

          let nombreZona = responseData.response.NOMBRE_ZONA;
          let comentarios = responseData.response.COMENTARIOS;

          this.formGroup.controls['CODIGO_ZONA'].setValue(this.idLevel);
          this.formGroup.controls['CODIGO_ZONA'].disable();
          this.formGroup.controls['NOMBRE_ZONA'].setValue(nombreZona);
          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.registerZone();
        }
      });
    } 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.updateZone();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }
  }

  private async registerZone() {
    const requestFormZone: RequestFormZone = this.createRequestForm();
    await lastValueFrom(this._warehouseService.registerZone(requestFormZone)).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 updateZone() {
    const requestFormZone: RequestFormZone = this.createRequestForm();
    const encZone: string = await this._encService.encrypt(this.idZone);
    await lastValueFrom(this._warehouseService.updateZone(requestFormZone, encZone)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación Existosa!`);
          this._dialogReg.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  private createRequestForm(): RequestFormZone {

    let codigoZona = null;
    if (this.typeDialog === 'REG') {
      codigoZona = this.formGroup.controls['CODIGO_ZONA'].value;
    }
    let nombreZona = this.formGroup.controls['NOMBRE_ZONA'].value;
    let comentarios = this.formGroup.controls['COMENTARIOS'].value;
    console.log(codigoZona);
    

    const requestFormZone: RequestFormZone = {
      CODIGO_ALMACEN: this.idWarehouse,
      CODIGO_AREA: this.idArea,
      CODIGO_NIVEL: this.idLevel,
      CODIGO_ZONA: codigoZona,
      NOMBRE_ZONA: nombreZona,
      COMENTARIOS: comentarios,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }

    return requestFormZone;
  }

}

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