import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CountriesList, CountriesListResponse, LadaSelection } from '../../../../../../interfaces/countries-list.interface';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { DataDialogReference, ReferenceData } from '../../../../../../interfaces/acquisition-management/provider.interface';
import { ResourcesService } from '../../../../../../services/resources.service';
import { SystemAdminService } from '../../../../../../services/system-admin.service';
import { validateRFC } from '../../../../../../../environments/environment.prod';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-references-form',
    templateUrl: './references-form.component.html',
    styleUrl: './references-form.component.css',
    standalone: false
})
export class ReferencesFormComponent implements OnInit {
  public formGroup: FormGroup;
  public arrCountries: Array<CountriesList>;
  public titleDialog: string;
  public isLoadingForm: boolean;

  filteredLadas?: Observable<string[]>;

  public ladasStr: string[];
  public ladas: LadaSelection[];
  public countriesStr: string[];
  flags: Map<string, string>;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DataDialogReference,
    public resourcesService: ResourcesService,
    private _dialogRef: MatDialogRef<Array<ReferenceData>>,
    private _sysAdminService: SystemAdminService,
  ) {
    if (dataDialog.typeDialog === 'REGISTER') {
      this.titleDialog = 'Registro de referencia';
    } else if (dataDialog.typeDialog === 'UPDATE') {
      this.titleDialog = 'Modificación de referencia';
    }else{
      this.titleDialog = 'Referencia';
    }
    this.formGroup = this.createFormGroup();

    this.isLoadingForm = false;
    this.arrCountries = [];
    this.countriesStr = [];
    this.ladasStr = [];
    this.ladas = [];

    this.flags = new Map();

  }

  private createFormGroup(){
    return new FormGroup({
      NUMERO_REFERENCIA: new FormControl(this.dataDialog.dataSource.length + 1, Validators.required),
      RAZON_SOCIAL: new FormControl('', Validators.required),
      RFC: new FormControl('', [Validators.required, Validators.pattern(new RegExp(validateRFC))]),
      CORREO: new FormControl('',[ Validators.required, Validators.email]),
      LADA: new FormControl('', Validators.required),
      TELEFONO: new FormControl('', Validators.required),
      DIRECCION: new FormControl('', Validators.required),
      ESTADO: new FormControl('Nuevo', Validators.required),
    });
  }

  async ngOnInit() {
    this.isLoadingForm = true;
    await this.setDataUpdate();
    await this.getCoutries();
    this.isLoadingForm = false;

    this.filteredLadas = this.formGroup.controls['LADA'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.ladasStr.filter((item) => item.toLowerCase().includes(filterValue));
      })
    );
  }

  private async setDataUpdate() {
    if (this.dataDialog.typeDialog === 'UPDATE' || this.dataDialog.typeDialog === 'ONLYREAD') {
      this.isLoadingForm = true;
      this.formGroup.controls['NUMERO_REFERENCIA'].setValue(this.dataDialog.dataElement.NUMERO_REFERENCIA);
      this.formGroup.controls['RAZON_SOCIAL'].setValue(this.dataDialog.dataElement.RAZON_SOCIAL);
      this.formGroup.controls['RFC'].setValue(this.dataDialog.dataElement.RFC);
      this.formGroup.controls['CORREO'].setValue(this.dataDialog.dataElement.CORREO);
      this.formGroup.controls['LADA'].setValue(this.dataDialog.dataElement.LADA);
      this.formGroup.controls['TELEFONO'].setValue(this.dataDialog.dataElement.TELEFONO);
      this.formGroup.controls['DIRECCION'].setValue(this.dataDialog.dataElement.DIRECCION);
      if (this.dataDialog.dataElement.ESTADO !== 'Nuevo') {
        this.formGroup.controls['ESTADO'].setValue('Modificado');
      }
      this.isLoadingForm = false;
    }
  }

  private async getCoutries() {
    const idUser: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._sysAdminService.getCountriesList(idUser, line)).then(
      async (responseData: CountriesListResponse) => {
        if (!responseData.error) {
          let mex = responseData.response.filter(item => item.COUNTRY_ID == 'MEX');
          this.arrCountries.push(mex[0]);
          this.countriesStr.push(`${mex[0].NAME} (${mex[0].COUNTRY_ID})`);
          this.flags.set(`${mex[0].LADA!}-${mex[0].NOMECLARUTA_ISO2!}`, mex[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${mex[0].LADA!}-${mex[0].NOMECLARUTA_ISO2!}`);

          let usa = responseData.response.filter(item => item.COUNTRY_ID == 'USA');
          this.arrCountries.push(usa[0]);
          this.countriesStr.push(`${usa[0].NAME} (${usa[0].COUNTRY_ID})`);
          this.flags.set(`${usa[0].LADA!}-${usa[0].NOMECLARUTA_ISO2!}`, usa[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${usa[0].LADA!}-${usa[0].NOMECLARUTA_ISO2!}`);

          let can = responseData.response.filter(item => item.COUNTRY_ID == 'CAN');
          this.arrCountries.push(can[0]);
          this.countriesStr.push(`${can[0].NAME} (${can[0].COUNTRY_ID})`);
          this.flags.set(`${can[0].LADA!}-${can[0].NOMECLARUTA_ISO2!}`, can[0].NOMECLARUTA_ISO2!);
          this.ladasStr.push(`${can[0].LADA!}-${can[0].NOMECLARUTA_ISO2!}`);
          
          for(const country of responseData.response){
            if(country.COUNTRY_ID != null && country.COUNTRY_ID != 'MEX' && country.COUNTRY_ID != 'USA' && country.COUNTRY_ID != 'CAN'){
              this.arrCountries.push(country);
              this.countriesStr.push(`${country.NAME} (${country.COUNTRY_ID})`);
              
              if(country.LADA != '' && country.NOMECLARUTA_ISO2 != '' && country.NOMECLARUTA_ISO2 != '0'){
                let currentURI = window.location.href;
                let currentURIArr = currentURI.split('#');
                let flagURI = `${currentURIArr[0]}assets/img/flags/${country.NOMECLARUTA_ISO2!}.png`;
                let fileExists = await this.resourcesService.fileExists(flagURI);

                if(fileExists){
                  this.flags.set(`${country.LADA!}-${country.NOMECLARUTA_ISO2!}`, country.NOMECLARUTA_ISO2!);
                  this.ladasStr.push(`${country.LADA!}-${country.NOMECLARUTA_ISO2!}`);
                }
              }
            }
          }

        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getCoutries();
        }
      }
    );
  }

  public registerReference() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ReferenceData> = this.dataDialog.dataSource;

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

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

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

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

    let LADA = this.formGroup.controls['LADA'].value;
    LADA = LADA.toString().trim();
    LADA = LADA.split('-')[0];

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

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

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

    const REQUEST_FORM = {
      NUMERO_REFERENCIA: NUMERO_REFERENCIA,
      RAZON_SOCIAL: RAZON_SOCIAL,
      RFC: RFC,
      CORREO: CORREO,
      LADA: LADA,
      TELEFONO: TELEFONO,
      DIRECCION: DIRECCION,
      ESTADO: ESTADO,
    }

    arrDataSource.push(REQUEST_FORM);
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }

  public updateReference() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ReferenceData> = this.dataDialog.dataSource;
    arrDataSource = arrDataSource.map((element: ReferenceData) => {
      if (element.NUMERO_REFERENCIA === this.formGroup.controls['NUMERO_REFERENCIA'].value) {

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

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

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

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

        let LADA = this.formGroup.controls['LADA'].value;
        LADA = LADA.toString().trim();
        LADA = LADA.split('-')[0];

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

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

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

        const REQUEST_FORM = {
          NUMERO_REFERENCIA: NUMERO_REFERENCIA,
          RAZON_SOCIAL: RAZON_SOCIAL,
          RFC: RFC,
          CORREO: CORREO,
          LADA: LADA,
          TELEFONO: TELEFONO,
          DIRECCION: DIRECCION,
          ESTADO: ESTADO,
        }

        element = REQUEST_FORM;
      }
      return element;
    });
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }
}
