import { NgClass } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { Roots } from '@enums/root.enum';
import { IonicModule, NavController } from '@ionic/angular';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';
@Component({
  selector: 'app-add-location',
  templateUrl: './add-location.page.html',
  styleUrls: ['./add-location.page.scss'],
  standalone: true,
  imports: [IonicModule, NgClass, FormsModule]
})
export class AddLocationPage implements OnInit {
  @ViewChild('Location') location: ElementRef;
  addLocation = '';
  addLocationLat = '';
  addLocationLong = '';
  type: number;
  constructor(
    private stateManagementService: StateManagementService,
    private navCtrl: NavController,
    private router: Router,
    private utilityService: UtilityService,
  ) {
    if (this.router.getCurrentNavigation().extras.state) {
      if (this.router.getCurrentNavigation().extras.state.type) {
        this.type = this.router.getCurrentNavigation().extras.state.type;
      }
    }
  }

  ngOnInit() {
    this.addLocation = this.router.getCurrentNavigation().extras.state.addLocation;
    this.addLocationLat = this.router.getCurrentNavigation().extras.state.addLocationLat;
    this.addLocationLong = this.router.getCurrentNavigation().extras.state.addLocationLong;
  }

  initAutocomplete(): void {
    this.utilityService.createAutocomplete(this.location.nativeElement, []).subscribe((details) => {
      this.addLocation = this.location.nativeElement.value;
      this.addLocationLat = details.geometry.location.lat();
      this.addLocationLong = details.geometry.location.lng();
    });
  }

  removeLatAndLong() {
    this.addLocationLat = '';
    this.addLocationLong = '';
  }

  submitLocation() {
    this.stateManagementService.postLocationSubject.next(this.addLocation);
    this.stateManagementService.postLocationLatSubject.next(this.addLocationLat);
    this.stateManagementService.postLocationLongSubject.next(this.addLocationLong);
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed);
  }
}
