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 { GetDataByPostalCode, ResponseDataPostalCode } from 'src/app/interfaces/locate/locate.interface';
import { LocateService } from 'src/app/services/locate/locate.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DispatchData, DispatchForm, DispatchRequest, ResponseDataDispatch, ResponseDataSuburb } from 'src/app/interfaces/acquisition-management/dispatch.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { DispatchService } from 'src/app/services/acquisition-management/dispatch.service';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-dispatch-form',
  templateUrl: './dispatch-form.component.html',
  styleUrls: ['./dispatch-form.component.css']
})
export class DispatchFormComponent implements OnInit {

  public titleDialog:string;
  public formGroup: FormGroup;

  public locate: GetDataByPostalCode;

  public isLoadingForm: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public element: any,
    public resourceService: ResourcesService,
    private _locateService: LocateService,
    private _dialogRef: MatDialogRef<DispatchFormComponent>,
    private _dispatchService: DispatchService,
    private _dialog: MatDialog,
  ) {
    this.titleDialog = element.typeForm === 'REG' ? 'Registro de Despacho' : 'Modificación de Despacho';
    this.formGroup = this.createFormGroup();
    this.locate = { } as GetDataByPostalCode;
    this.isLoadingForm = false;
  }

  ngOnInit(): void {
    if (this.element.typeForm === 'UPD') {
      this.setDataForm();
    }
  }

  private createFormGroup(): FormGroup{
    return new FormGroup({
      NUMERO_DESPACHO: new FormControl(''),
      DESPACHO: new FormControl('', Validators.required),
      CALLE: new FormControl('', Validators.required),
      NUMEROEXTERIOR: new FormControl('', Validators.required),
      NUMEROINTERIOR: new FormControl(''),
      CODIGOPOSTAL: new FormControl('', Validators.required),
      COLONIA: new FormControl('', Validators.required),
      MUNICIPIO: new FormControl('', Validators.required),
      ENTIDAD: new FormControl('', Validators.required),
      PAIS: new FormControl('', Validators.required),
    });
  }

  public async alert(type: string, dataElement: any = null): Promise<void> {
    this.isLoadingForm = true;
    let dataDialog: AlertData = {} as AlertData;

    if ( this.element.typeForm === 'REG') {
      dataDialog = {
        icon: "warning",
        title: "Registro de Despacho",
        description: "¿Está seguro de registrar el despacho?"
      };
    }else if (this.element.typeForm === 'UPD') {
      dataDialog = {
        icon: "warning",
        title: "Modificación de Despacho",
        description: "¿Está seguro de modificar el despacho?"
      };
    }

    this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
    }).afterClosed().subscribe((result) => {

      if (result && this.element.typeForm === 'REG') {
        this.registerDispatch();
      } else if (result && this.element.typeForm === 'UPD') {
        this.updateDispatch();
      }else{
        this.isLoadingForm = false;
      }
    });
  }

  private async registerDispatch() {
    const requestDispatch: DispatchRequest = await this.createRequest();

    await lastValueFrom(this._dispatchService.registerDispatch(requestDispatch)).then(
      ( responseData: ResponseData ) => {
        if (! responseData.error){
          this.resourceService.openSnackBar('¡Registro Exitoso!');
          this._dialogRef.close(true);
        } else {
          this.resourceService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );

    this.isLoadingForm = false;
  }

  private async updateDispatch() {
    const requestDispatch: DispatchRequest = await this.createRequest();

    await lastValueFrom(this._dispatchService.updateDispatch(requestDispatch)).then(
      ( responseData: ResponseData ) => {
        if(! responseData.error){
          this.resourceService.openSnackBar('¡Modificación Exitosa!');
          this._dialogRef.close(true);
        } else {
          this.resourceService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );

    this.isLoadingForm = false;
  }

  private async createRequest() {
    const objRequest: DispatchRequest = {
      NUMERO_DESPACHO: this.NUMERO_DESPACHO.value === null ? '' : this.NUMERO_DESPACHO.value.toString().trim(),
      DESPACHO: this.DESPACHO.value === null ? '' : this.DESPACHO.value.toString().trim(),
      CALLE: this.CALLE.value === null ? '' : this.CALLE.value.toString().trim(),
      NUMERO_EXTERIOR: this.NUMEROEXTERIOR.value === null ? '' : this.NUMEROEXTERIOR.value.toString().trim(),
      NUMERO_INTERIOR: this.NUMEROINTERIOR.value === null ? '' : this.NUMEROINTERIOR.value.toString().trim(),
      CODIGO_POSTAL: this.CODIGOPOSTAL.value === null ? '' : this.CODIGOPOSTAL.value.toString().trim(),
      COLONIA: this.COLONIA.value === null ? '' : this.COLONIA.value.toString().trim(),
      MUNICIPIO: this.MUNICIPIO.value === null ? '' : this.MUNICIPIO.value.toString().trim(),
      ENTIDAD: this.ENTIDAD.value === null ? '' : this.ENTIDAD.value.toString().trim(),
      PAIS: this.PAIS.value === null ? '' : this.PAIS.value.toString().trim(),
      USUARIO: this.resourceService.getUser(),
      NUMERO_LINEA: '1'
    }

    return objRequest;
  }

  private async setDataForm () {
    this.isLoadingForm = true;
    this.NUMERO_DESPACHO.disable();
    this.DESPACHO.disable();
    this.CALLE.disable();
    this.NUMEROEXTERIOR.disable();
    this.NUMEROINTERIOR.disable();
    this.CODIGOPOSTAL.disable();
    this.COLONIA.disable();
    this.MUNICIPIO.disable();
    this.ENTIDAD.disable();
    this.PAIS.disable();

    await this.getSuburbByPostalCode(this.element.dataElement.DESP_COPO);
    this.NUMERO_DESPACHO.enable();
    this.DESPACHO.enable();
    this.CALLE.enable();
    this.NUMEROEXTERIOR.enable();
    this.NUMEROINTERIOR.enable();
    this.CODIGOPOSTAL.enable();
    this.COLONIA.enable();
    this.MUNICIPIO.enable();
    this.ENTIDAD.enable();
    this.PAIS.enable();

    this.NUMERO_DESPACHO.setValue(this.element.dataElement.DESP_NUDE);
    this.CODIGOPOSTAL.setValue(this.element.dataElement.DESP_COPO);
    this.DESPACHO.setValue(this.element.dataElement.DESP_NOMB);
    this.CALLE.setValue(this.element.dataElement.DESP_CALL);
    this.NUMEROEXTERIOR.setValue(this.element.dataElement.DESP_NUEX);
    this.NUMEROINTERIOR.setValue(this.element.dataElement.DESP_NUIN);
    this.COLONIA.setValue(this.element.dataElement.DESP_COLO);
    this.MUNICIPIO.setValue(this.element.dataElement.DESP_MUNI);
    this.ENTIDAD.setValue(this.element.dataElement.DESP_ENTI);
    this.PAIS.setValue(this.element.dataElement.DESP_PAIS);
    this.isLoadingForm = false;
  }

  public async getSuburb() {
    let postalCode: string = this.CODIGOPOSTAL.value.toString();
    console.log(postalCode);


    if ( postalCode.length === 5) {
      this.CODIGOPOSTAL.disable();
      this.COLONIA.disable();
      this.MUNICIPIO.disable();
      this.ENTIDAD.disable();
      this.PAIS.disable();

      this.COLONIA.setValue('');
      this.MUNICIPIO.setValue('');
      this.ENTIDAD.setValue('');
      this.PAIS.setValue('');

      await this.getLocateByPostalCode(postalCode.toString());
      this.CODIGOPOSTAL.enable();
      this.COLONIA.enable();
      this.MUNICIPIO.enable();
      this.ENTIDAD.enable();
      this.PAIS.enable();
    }
  }

  private async getLocateByPostalCode(postalCode: string){
    this.isLoadingForm = true;
    await lastValueFrom(this._locateService.getDataByPostalCode(postalCode)).then(
      (responseData: ResponseDataPostalCode) => {
        if ( !responseData.error ) {
          this.locate = responseData.response;
          this.MUNICIPIO.setValue(this.locate.MUNICIPALITY);
          this.ENTIDAD.setValue(this.locate.STATE);
          this.PAIS.setValue(this.locate.COUNTRY);
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async getSuburbByPostalCode(postalCode: string){
    this.isLoadingForm = true;
    await lastValueFrom(this._locateService.getSuburbByPostalCode(postalCode)).then(
      (responseData: ResponseDataSuburb) => {
        if ( !responseData.error ) {
          this.locate.SUBURB = responseData.response;
        }
      }, (error: HttpErrorResponse) => this.resourceService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }


  get NUMERO_DESPACHO() { return this.formGroup.get('NUMERO_DESPACHO')!; }
  get DESPACHO() { return this.formGroup.get('DESPACHO')!; }
  get CALLE() { return this.formGroup.get('CALLE')!; }
  get NUMEROEXTERIOR() { return this.formGroup.get('NUMEROEXTERIOR')!; }
  get NUMEROINTERIOR() { return this.formGroup.get('NUMEROINTERIOR')!; }
  get CODIGOPOSTAL() { return this.formGroup.get('CODIGOPOSTAL')!; }
  get COLONIA() { return this.formGroup.get('COLONIA')!; }
  get MUNICIPIO() { return this.formGroup.get('MUNICIPIO')!; }
  get ENTIDAD() { return this.formGroup.get('ENTIDAD')!; }
  get PAIS() { return this.formGroup.get('PAIS')!; }

}
