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

@Component({
  selector: 'app-references-form',
  templateUrl: './references-form.component.html',
  styleUrls: ['./references-form.component.css']
})
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[];

  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 = [];

  }

  ngOnInit(): void {
    this.setDataUpdate();
    this.getCoutries();

    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 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 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(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      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),
    });
  }

  private async getCoutries() {
    const idUser: string = this.resourcesService.getUser();
    const line: number = parseInt(this.resourcesService.getLineNumber());
    await lastValueFrom(this._sysAdminService.getCountriesList(idUser, line)).then(
      (responseData: CountriesListResponse) => {
        if (!responseData.error) {
          this.arrCountries = responseData.response;

          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})`);

          let mexLada: LadaSelection = {
            FLAG: [mex[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: mex[0].LADA!
          };          
          
          this.ladas.push(mexLada);
          this.ladasStr.push(`${mexLada.FLAG} ${mexLada.LADA}`);

          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})`);

          let usaLada: LadaSelection = {
            FLAG: [usa[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: usa[0].LADA!
          };
          
          this.ladas.push(usaLada);
          this.ladasStr.push(`${usaLada.FLAG} ${usaLada.LADA}`);

          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})`);

          let canLada: LadaSelection = {
            FLAG: [can[0].NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
            LADA: can[0].LADA!
          };
          
          this.ladas.push(canLada);
          this.ladasStr.push(`${canLada.FLAG} ${canLada.LADA}`);
                    
          responseData.response.forEach(country => {
            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})`);

              try{
                flag(country.NOMECLARUTA_ISO2!);
                let hasLada = country.LADA != '';

                if(hasLada){
                  let lada: LadaSelection = {
                    FLAG: [country.NOMECLARUTA_ISO2!].map(countryCodeEmoji)[0],
                    LADA: country.LADA!
                  };

                  this.ladas.push(lada);
                  this.ladasStr.push(`${lada.FLAG} ${lada.LADA}`);
                }
              }catch(error: any){
                //Saltar país
              }
            }
          });

        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public registerReference() {
    this.isLoadingForm = true;
    let arrDataSource: Array<ReferenceData> = this.dataDialog.dataSource;
    arrDataSource.push(this.formGroup.value);
    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) {
        element = this.formGroup.value;
      }
      return element;
    });
    this._dialogRef.close(arrDataSource);
    this.isLoadingForm = false;
  }
}
