import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, Subscription, throwError } from 'rxjs';
import { catchError, map, tap, switchMap } from 'rxjs/operators';
import { CustomerAddress } from 'src/app/models/customer-address.model';
import { Place } from 'src/app/models/places.model';
import { AddressCustomerService } from 'src/app/services/address-customer.service';
import { CustomerService } from 'src/app/services/customer.service';
import { LookupService } from 'src/app/services/lookup.service';
import { ConsultaCepService } from 'src/app/shared/services/consulta-cep.service';

@Component({
  selector: 'app-create-address-modal',
  templateUrl: './create-address-modal.component.html',
  styleUrls: ['./create-address-modal.component.scss',
    '../../../shared/styles/button-style.scss']
})
export class CreateAddressModalComponent implements OnInit {
  public customerAddress: CustomerAddress;
  public isloading = false;
  public errorObject: any;
  public result;
  loaderVisible = false;
  @Input() openedDialog = false;
  @Input() customerId: number;
  @ViewChild('formCustomer') formCustomer: ElementRef;
  @ViewChild('inputCpf') inputCpf: ElementRef;
  @Output() resultEvent = new EventEmitter<CustomerAddress>();
  subscriptionAddress: Subscription;

  places$: Observable<Place[]>;
  places: Place[] = [];
  place: Place;
  subscriptionPlaces: Subscription;

  public windowWidth = 600;
  public windowHeight = 650;

  public isShowConfirmation = false;
  titleMessage = 'Cadastro de endereço';
  messageConfirmation = 'Confirma dados para o endereço de entrega?';
  textButtonConfirmation = 'Confirmar';
  textButtonCancel = 'Cancelar';

  //mostrar mapa
  showMap = false;
  latitude = -1.3819925;
  longitude = -48.4084447;
  zoom = 15;


  public form: FormGroup;

  public addressData: any = {
    address: '',
    addressNumber: '',
    complement: '',
    neighborhood: '',
    city: '',
    state: '',
    zipCode: '',
    referencePoint: '',
    note: '',
    latitude: 0,
    longitude: 0,
    addressType: '',
  };

  constructor(
    private readonly addressService: AddressCustomerService,
    private cepService: ConsultaCepService,
    private lookupService: LookupService,) {
    this.form = new FormGroup({
      address: new FormControl(this.addressData.address, [Validators.required]),
      addressNumber: new FormControl(this.addressData.addressNumber, [Validators.required]),
      neighborhood: new FormControl(this.addressData.neighborhood, [Validators.required]),
      complement: new FormControl(this.addressData.complement, [Validators.required]),
      city: new FormControl(this.addressData.city, [Validators.required]),
      state: new FormControl(this.addressData.state, [Validators.required]),
      zipCode: new FormControl(this.addressData.zipCode),
      referencePoint: new FormControl(this.addressData.referencePoint),
      ibgeCode: new FormControl(this.addressData.ibgeCode),
      note: new FormControl(this.addressData.note),
      place: new FormControl(null, [Validators.required]),
      latitude: new FormControl(this.addressData.latitude, []),
      longitude: new FormControl(this.addressData.longitude, []),
      addressType: new FormControl(this.addressData.addressType)
    });
  }

  ngOnInit(): void {
    this.places$ = this.lookupService.getPlaces();
    this.subscriptionPlaces = this.places$.subscribe(data => this.places = data);
  }


  populateAddressCustomer(data: CustomerAddress) {
    this.form.patchValue({
      zipCode: data.zipCode,
      address: data.street,
      addressNumber: data.numberAddress,
      complement: data.complement,
      neighborhood: data.neighbourhood,
      city: data.city,
      state: data.state,
      referencePoint: data.referencePoint,
      note: data.note,
      latitude: data.latitude,
      longitude: data.longitude,
      addressType: data.addressType
    });

  }

  public closeDialog(result = false) {
    this.openedDialog = false;
    this.resultEvent.emit(this.customerAddress);
  }

  createCustomer() {
    /*console.log(this.form.value);
    const result$ = this.customerService.createCustomer(this.form.value);
    result$.pipe(
      map(c => {
        this.customer = c.data;
      }),
    ).subscribe();*/
  }

  async consultaCep() {
    const cep = this.form.get('zipCode').value;
    this.subscriptionAddress = this.addressService
      .getAddressByCep(this.customerId, cep)
      .pipe(
        tap((address) => {
          // this.customerAddress = address;
          console.log('Endereço: ' + JSON.stringify(address));
          if (address != null) {
            const places = this.places.filter(p => p.id === address.placeId);
            if (places.length > 0) {
              this.place = places[0];
            }

            this.populateAddressCustomer(address);

            //             this.form.patchValue({
            //               address: address.enderent,
            //               addressNumber: address.numeroent,
            //               complement: address.complementoent,
            //               neighborhood: address.bairroent,
            //               city: address.municent,
            //               state: address.estent,
            //               referencePoint: address.pontorefer,
            // //              ibgeCode: address.ibgeCode
            //             });

            if (this.place != null) {
              this.form.patchValue({
                place: this.place,
              });
            }

          }
        }),
        switchMap(data => {
          return this.cepService.consultaCep(cep);
        }),
        tap(dados => {
          if (this.customerAddress == null && dados != null) {
            this.populateAddress(dados);
          }
        })
      )
      .subscribe();

    // if (cep != null && cep !== '') {
    //   this.cepService.consultaCep(cep)
    //     .subscribe(
    //       dados => {
    //         if (dados != null) {
    //           this.populateAddress(dados);
    //         }
    //       });
    // }
  }

  populateAddress(dadosCep: any) {
    console.log('Dados do Cep: ' + dadosCep);
    let city = dadosCep.cidade as string;
    if (city.length > 15) {
      city = city.substring(0, 15);
    }
    this.form.patchValue({
      address: dadosCep.logradouro.toUpperCase(),
      //complement: dadosCep.complemento.toUpperCase(),
      neighborhood: dadosCep.bairro.toUpperCase(),
      city, //: dadosCep.cidade.toUpperCase(),
      state: dadosCep.uf.toUpperCase(),
      ibgeCode: dadosCep.codigo_ibge,
      latitude: dadosCep.lat,
      longitude: dadosCep.lon,
    });
  }

  showConfirmation() {
    this.isShowConfirmation = true;
  }

  returnConfirmationSalve(result: any) {
    this.customerAddress = null;
    this.isShowConfirmation = false;
    let placeId = 0;
    if (this.form.get('place').value != null) {
      const place = this.form.get('place').value;
      placeId = place.id;
    }
    if (result) {
      const address: CustomerAddress = {
        idCustomer: this.customerId,
        idAddress: null,
        street: this.form.get('address').value,
        numberAddress: this.form.get('addressNumber').value,
        complement: this.form.get('complement').value,
        neighbourhood: this.form.get('neighborhood').value,
        city: this.form.get('city').value,
        state: this.form.get('state').value,
        zipCode: this.form.get('zipCode').value,
        referencePoint: this.form.get('referencePoint').value,
        note: this.form.get('note').value,
        ibgeCode: this.form.get('ibgeCode').value,
        placeId,
        latitude: this.form.get('latitude').value,
        longitude: this.form.get('longitude').value,
        addressType: this.form.get('addressType').value,
      };
      const result$ = this.addressService.createAddress(address);
      result$.pipe(
        map(c => {
          this.customerAddress = c.data;
          console.log(c);
        }),
      ).subscribe(() => {
        this.closeDialog(true);
      }
      );
    }
  }

  removeCharacters(field: string) {
    const text = this.form.get(field).value;
    console.log(text);
    const str = text.normalize('NFD').replace(/[^a-zA-Z\s0-9]/g, '').toUpperCase();
    switch (field) {
      case 'name':
        this.form.patchValue({
          name: str,
        });
        return;
      case 'address':
        this.form.patchValue({
          address: str,
        });
        return;
      case 'neighborhood':
        this.form.patchValue({
          neighborhood: str,
        });
        return;
      case 'complement':
        this.form.patchValue({
          complement: str,
        });
        return;
      case 'city':
        this.form.patchValue({
          city: str,
        });
        return;
      case 'state':
        this.form.patchValue({
          state: str,
        });
        return;
      case 'comments':
        this.form.patchValue({
          comments: str,
        });
        return;
      default:
        return;
    }
  }

  // MapCep(show: boolean) {
  //   if (show) {
  //     const customer = JSON.parse(localStorage.getItem('address')) as CustomerAddress;
  //     console.log(this.form);
  //     this.latitude = this.form.get('latitude').value;
  //     this.longitude = this.form.get('longitude').value;

  //     if (this.latitude == 0 && customer != null) {
  //       this.latitude = customer.latitude;
  //       this.longitude = customer.longitude;
  //     }
  //     console.log("Latitude: " + this.latitude + ", Longitude: " + this.longitude);
  //   }

  //   this.showMap = show;
  // }

  MapCep(show: boolean, latitude?: number, longitude?: number) {
    if (show) {
      const customer = JSON.parse(localStorage.getItem('address')) as CustomerAddress;
      console.log(this.form);
      this.latitude = latitude; //Number.parseFloat((this.form.get('latitude').value as string).replace(',', '.'));
      this.longitude = longitude; //Number.parseFloat((this.form.get('longitude').value as string).replace(',', '.'));

      // if ( this.latitude == 0 && customer != null ) {
      //   this.latitude  = customer.latitude;
      //   this.longitude = customer.longitude;
      // }
    }

    this.showMap = show;
  }

  async googleGeocode() {
    const address = this.form.get('address').value;
    const addressNumber = this.form.get('addressNumber').value;
    const neighborhood = this.form.get('neighborhood').value;
    const city = this.form.get('city').value;
    const state = this.form.get('state').value;

    console.log(address);
    console.log(addressNumber);
    console.log(neighborhood);
    console.log(city);
    console.log(state);

    this.cepService.googleGeocode(address, addressNumber, neighborhood, city, state)
      .pipe(
        map(result => {
          console.log(result);
          this.MapCep(true, result[0].latitude, result[0].longitude);
        })
      )
      .subscribe();
  }

}
