import { NgIf } from '@angular/common';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormsModule, NgModel } from '@angular/forms';
import { IonicSelectableItemTemplateDirective } from '@components/ionic-selectable/ionic-selectable-item-template.directive';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { IdName, SanghData } from '@interfaces/common';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';

enum ADDRESS_TYPE {
  Location = 1,
  Sangh = 2
}

@Component({
  selector: 'app-sant-location',
  templateUrl: './sant-location.component.html',
  styleUrls: ['./sant-location.component.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, IonicSelectableComponent, IonicSelectableItemTemplateDirective]
})
export class SantLocationComponent implements OnInit {
  @Input() santDetails: any;
  @Output() updated = new EventEmitter();
  @ViewChild('Location') location: ElementRef;
  @ViewChild('confirm') confirm: NgModel;
  @ViewChild('sanghListComponent') sanghListComponent: IonicSelectableComponent;
  addLocation = '';
  addLocationLat = '';
  addLocationLong = '';
  isModalOpen = false;
  addressType: ADDRESS_TYPE = ADDRESS_TYPE.Location;
  sanghList: Array<SanghData> = [];
  selectedSangh: IdName = null;
  sanghPageNumber = 1;
  sanghTotalPages = 1;
  sanghSearchText = '';
  prevValue = '';
  confirmed = false;

  constructor(
    private utilityService: UtilityService,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private change: ChangeDetectorRef,
    private navController: NavController,
    private stateManagementService: StateManagementService
  ) { }

  async ngOnInit() {
    this.addressType = this.santDetails.sant_location_type || ADDRESS_TYPE.Location;
    if (this.santDetails.sant_location_type === ADDRESS_TYPE.Sangh) {
      this.selectedSangh = { id: this.santDetails.sant_location_sangh_id, name: this.santDetails.sant_location };
    } else if (this.santDetails.sant_location_type === ADDRESS_TYPE.Location) {
      this.addLocation = this.santDetails.sant_location;
      this.addLocationLat = this.santDetails.sant_location_latitude;
      this.addLocationLong = this.santDetails.sant_location_longitude;
    }
    this.change.detectChanges();
    await this.getSanghList();
  }

  address(element) {
    this.utilityService.openGoogleMap(element.sant_location_latitude, element.sant_location_longitude);
  }

  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 = '';
  }

  searchSangh(event: { component: IonicSelectableComponent; text: string }) {
    const isSameStr = this.utilityService.isSameStr(event.text, this.prevValue);
    this.prevValue = event.text;
    if (!isSameStr) {
      this.sanghPageNumber = 1;
      this.sanghList = [];
      this.sanghSearchText = event.text;
      event.component.showLoading();
      this.getSanghList().then(() => {
        event.component.hideLoading();
      });
    }
  }


  getSanghList() {
    return this.httpRequestService.get(api.sanghSearchList, {
      name: this.sanghSearchText,
      page: this.sanghPageNumber,
      limit: 15
    }).then((res: any) => {
      this.sanghList.push(...res.data.data);
      this.sanghTotalPages = res.data.last_page;
    });
  }

  addSangh(sangh) {
    this.selectedSangh = {
      id: sangh.value.id,
      name: sangh.value.name
    };
    this.sanghListComponent.searchText = '';
    this.sanghList = [];
    this.sanghSearchText = '';
    this.sanghPageNumber = 1;
    this.getSanghList();
  }

  getMoreSangh(event: { component: IonicSelectableComponent; text: string }) {
    if (this.sanghPageNumber >= this.sanghTotalPages) {
      event.component.disableInfiniteScroll();
      return;
    }
    this.sanghPageNumber++;
    this.getSanghList().then(() => {
      event.component.endInfiniteScroll();
    });
  }

  submitLocation() {
    this.confirm.control.markAsDirty();
    if (!this.confirmed) { return; }

    this.alert.showLoader();
    this.httpRequestService.post(api.updateSantLocation, {
      sant_id: this.santDetails.id,
      ...this.addressType === ADDRESS_TYPE.Location && {
        location: this.addLocation,
        latitude: this.addLocationLat,
        longitude: this.addLocationLong
      },
      ...this.addressType === ADDRESS_TYPE.Sangh && {
        sangh_id: this.selectedSangh.id
      }
    }).then((res: any) => {
      this.isModalOpen = false;
      this.alert.showToaster(res.message);
      this.updated.emit(true);
    }).finally(() => {
      this.confirmed = false;
      this.alert.hideLoader();
    });
  }

  async goToProfile() {
    if (this.santDetails.sant_location_updated_by.name || this.santDetails.sant_location_created_by.name) {
      const userData = await this.stateManagementService.storage.get(GJainStorage.userData);
      const id = this.santDetails.sant_location_updated_by.id || this.santDetails.sant_location_created_by.id;
      if (id === userData.id) {
        this.navController.navigateForward(Roots.page + '/' + Roots.shravakViewProfile);
      } else {
        this.navController.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile.replace(':id', id)]);
      }
    }
  }

}
