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 { RequestFormArea, ResponseDataAreaWarehouse } 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-area-form',
  templateUrl: './area-form.component.html',
  styleUrls: ['./area-form.component.css']
})
export class AreaFormComponent implements OnInit {

  public formGroup: FormGroup;

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

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataFormArea: DataFormArea,
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _warehouseService: WarehouseService,
    private _dialog: MatDialog,
    private _dialogReg: MatDialogRef<boolean>,
  ) {
    this.formGroup = this.createFormGroup();

    this.isLoading = false;
    this.isLoadingForm = false;

    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_AREA: new FormControl('', Validators.required),
      NOMBRE_AREA: new FormControl('', Validators.required),
      COMENTARIOS: new FormControl(''),
    });
  }

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

  private async getAreaById() {
    const encArea: string = await this._encService.encrypt(this.idArea);
    await lastValueFrom(this._warehouseService.getAreaById(encArea)).then(
      (responseData: ResponseDataAreaWarehouse) => {
        if (!responseData.error && Object.keys(responseData.response).length > 0) {
          
          let numeroArea = this.idArea;
          let nombreArea = responseData.response.NOMBRE_AREA;
          let comentarios = responseData.response.COMENTARIOS;

          this.formGroup.controls['CODIGO_AREA'].disable();
          this.formGroup.controls['CODIGO_AREA'].setValue(numeroArea);
          this.formGroup.controls['NOMBRE_AREA'].setValue(nombreArea);
          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 área?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.registerArea();
        }
      });
    } 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 área?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.updateArea();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
    }
  }

  private async registerArea() {
    const requestFormArea: RequestFormArea = this.createRequestForm();
    await lastValueFrom(this._warehouseService.registerArea(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 updateArea() {
    const requestFormArea: RequestFormArea = this.createRequestForm();
    const encArea: string = await this._encService.encrypt(this.idArea);
    await lastValueFrom(this._warehouseService.updateArea(requestFormArea, encArea)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Modificación Exitosa!`);
          this._dialogReg.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  private createRequestForm(): RequestFormArea {

    let numeroArea = null;
    if (this.typeDialog === 'REG') {
      numeroArea = this.formGroup.controls['CODIGO_AREA'].value;
      numeroArea = numeroArea.toString().trim();
    }

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

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

    const requestFormArea: RequestFormArea = {
      CODIGO_ALMACEN: this.idWarehouse,
      CODIGO_AREA: numeroArea,
      NOMBRE_AREA: nombreArea,
      COMENTARIOS: comentarios,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }

    return requestFormArea;
  }

}

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