import { DOCUMENT, NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, Inject, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AvatarPercentageComponent } from '@components/avatar-percentage/avatar-percentage.component';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { Dharma, Sampraday } from '@interfaces/common';
import { IonicModule, ModalController, NavController } from '@ionic/angular';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-search-sant',
  templateUrl: './search-sant.page.html',
  styleUrls: ['./search-sant.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgIf, NgFor, AvatarPercentageComponent, IonicSelectableComponent]
})
export class SearchSantPage implements OnInit, OnDestroy {
  @ViewChild('currentLocation') currentLocation: ElementRef;
  santList = [];
  pageNumber = 1;
  totalPage = 1;
  searchValue = '';
  prevValue: string;
  dharma_id: any;
  sampraday_id: any;
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  gender_id: any;
  sampradayData = [];
  spinnerFlag = false;
  locationData = {
    text: '',
    lng: '',
    lat: ''
  };

  constructor(
    private httpRequestService: HttpRequestService,
    private navController: NavController,
    private modalCtrl: ModalController,
    private stateManagementService: StateManagementService,
    private renderer: Renderer2,
    private utilityService: UtilityService,
    @Inject(DOCUMENT) private document: Document,
  ) {
    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    if (this.stateManagementService.sampradayDetails.length > 0) {
      this.sampradayDetails = this.stateManagementService.sampradayDetails;
    } else {
      this.getSampradayDetails();
    }
    this.renderer.addClass(this.document.body, 'sant-selectable');
  }

  ngOnInit() {
    this.getSantList(false, '');
  }

  searchSant() {
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.santList = [];
      this.pageNumber = 1;
      this.totalPage = 1;
      this.getSantList(false, '');
    }
  }

  loadData($event) {
    this.getSantList(true, $event);
  }

  getSantList(isFirstLoad, event) {
    this.spinnerFlag = false;
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.post(api.globalSearchSant, {
        page: this.pageNumber,
        limit: 15,
        name: this.searchValue.trim(),
        dharma_id: this.dharma_id ? [this.dharma_id] : [],
        sampraday_id: this.sampradayData,
        gender_id: this.gender_id ? [this.gender_id] : [],
        longitude: this.locationData.text ? this.locationData.lng : '',
        latitude: this.locationData.text ? this.locationData.lat : '',
      }).then((res: any) => {
        if (isFirstLoad) { event.target.complete(); }
        if (!event) { this.santList = []; }
        this.totalPage = res.data.last_page;
        this.santList.push(...res.data.data);
        this.spinnerFlag = true;
        this.pageNumber++;
      });
    } else {
      event.target.complete();
      this.spinnerFlag = false;
    }
  }

  santProfile(santId) {
    this.navController.navigateForward(Roots.page + '/' + Roots.santViewProfile.replace(':santId', santId));
  }

  followSant(event, santId, index) {
    event.stopPropagation();
    this.httpRequestService.post(api.followSant, {
      sant_id: santId,
    }).then(() => {
      this.santList[index].is_user_following = !this.santList[index].is_user_following;
    });
  }

  onDharmChange() {
    this.sampraday_id = [];
    this.getSampradayDetails();
  }

  getDharmaDetails() {
    this.httpRequestService.get(api.dharmaDetails).then((res: any) => {
      this.dharmaDetails = res.data;
      this.stateManagementService.dharmaDetails = res.data;
    });
  }

  getSampradayDetails() {
    this.httpRequestService.get(api.sampradayDetails, {
      dharma_id: this.dharma_id
    }).then((res: any) => {
      this.sampradayDetails = res.data;
      this.stateManagementService.sampradayDetails = res.data;
    });
  }

  onSampradayChange() {
    this.sampradayData = [];
    for (const data of this.sampraday_id) {
      this.sampradayData.push(data.id);
    }
  }

  advanceSearch() {
    this.santList = [];
    this.pageNumber = 1;
    this.totalPage = 1;
    this.getSantList(false, '');
    this.modalCtrl.dismiss();
  }

  resetFilter() {
    this.dharma_id = '';
    this.sampraday_id = '';
    this.gender_id = '';
    this.locationData.text = '';
    this.sampradayData = [];
    this.advanceSearch();
  }

  initAutocompleteCurrent(): void {
    this.utilityService.createAutocomplete(this.currentLocation.nativeElement, []).subscribe((details) => {
      this.locationData = {
        text: this.currentLocation.nativeElement.value,
        lng: details.geometry.location.lng(),
        lat: details.geometry.location.lat()
      };
    });
  }

  ngOnDestroy(): void {
    this.renderer.removeClass(this.document.body, 'sant-selectable');
  }

}
