import { NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { Countries, Country } from '@interfaces/common';
import { SanghAddressForm } from '@interfaces/form';
import { IonicModule, NavController } from '@ionic/angular';
import { HttpRequestService } from '@services/http-request.service';
import { SantInfoService } from '@services/sant-info.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
@Component({
  selector: 'app-sangh-address',
  templateUrl: './sangh-address.page.html',
  styleUrls: ['./sangh-address.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, ReactiveFormsModule, NgIf, IonicSelectableComponent, NgFor]
})
export class SanghAddressPage implements OnInit {
  @ViewChild('Location') Location: ElementRef;
  sanghAddressForm: FormGroup<SanghAddressForm>;
  countryCodes: Array<Country> = [];
  members = [];
  numLength = 10;
  constructor(
    private navCtrl: NavController,
    public santService: SantInfoService,
    private utilityService: UtilityService,
    private stateManagementService: StateManagementService,
    private httpRequestService: HttpRequestService
  ) { }

  ngOnInit() {
    this.sanghAddressForm = this.santService.sanghAddressForm;
    this.members = this.stateManagementService?.common?.data?.number_of_members ?? [];
    if (this.stateManagementService.countryDetails.length > 0) {
      this.countryCodes = this.stateManagementService.countryDetails;
      this.setDefaultCountryCode();
    } else {
      this.fetchCountryCodes();
    }
  }

  setDefaultCountryCode() {
    this.countryCodes.forEach((elem) => {
      if (elem.iso === 'IN') {
        this.sanghAddressForm.controls.phoneCode.setValue(elem);
        this.codeChange({ value: { num_length: 10 } })
      }
    });
  }

  fetchCountryCodes() {
    this.httpRequestService.get(api.countryCodes).then((res: Countries) => {
      this.countryCodes = res.countries;
      this.stateManagementService.countryDetails = res.countries;
      if (this.countryCodes) {
        this.setDefaultCountryCode();
      }
    });
  }

  codeChange(event) {
    this.numLength = event.value.num_length;
    this.sanghAddressForm.controls.mobile_number.setValidators([Validators.required, Validators.pattern(`^[0-9]{${this.numLength}}$`)]);
  }

  initAutocomplete(): void {
    this.utilityService.createAutocomplete(this.Location.nativeElement, []).subscribe((details) => {
      const { city, state, apartment } = this.getCityAndState(details.address_components);

      city && this.sanghAddressForm.controls.city.setValue(city);
      state && this.sanghAddressForm.controls.state.setValue(state);
      apartment && this.sanghAddressForm.controls.apartment_name.setValue(apartment);
      this.sanghAddressForm.controls.address.setValue(this.Location.nativeElement.value);
      this.sanghAddressForm.controls.latitude.setValue(details.geometry.location.lat());
      this.sanghAddressForm.controls.longitude.setValue(details.geometry.location.lng());
    });
  }

  getCityAndState(addressComponents: any): { city: string, state: string, apartment: string } {
    let city = '';
    let state = '';
    let apartment = '';

    addressComponents.forEach(component => {
      const types = component.types;
      if (types.includes('locality')) {
        city = component.long_name;
      }
      if (types.includes('administrative_area_level_1')) {
        state = component.long_name;
      }
      if (types.includes('subpremise')) {
        apartment = component.long_name;
      }
    });

    return { city, state, apartment };
  }

  removeLatAndLong() {
    this.sanghAddressForm.controls.latitude.reset();
    this.sanghAddressForm.controls.longitude.reset();
  }

  moveToNext() {
    if (!this.sanghAddressForm.valid) {
      this.sanghAddressForm.markAllAsTouched();
      return;
    }
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghFacilities);
  }
}
