import { DOCUMENT, NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, Inject, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
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 { CommonResponse, Dharma, Sampraday, UserData } from '@interfaces/common';
import { IonicModule, ModalController, 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';
@Component({
  selector: 'app-sangh-search-member',
  templateUrl: './sangh-search-member.page.html',
  styleUrls: ['./sangh-search-member.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgIf, NgFor, IonicSelectableComponent]
})
export class SanghSearchMemberPage implements OnInit, OnDestroy {
  @ViewChild('personalLocation') personalLocation: ElementRef;
  sanghList = [];
  pageNumber = 1;
  totalPage = 1;
  searchValue = '';
  dharma_id: any;
  sampraday_id: any;
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  location: any;
  longitude = '';
  latitude = '';
  spinnerFlag = false;
  sampradayData = [];
  userData: UserData;
  prevValue: string;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private modalCtrl: ModalController,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document,
    private utilityService: UtilityService
  ) {
    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, 'sangh-selectable');
  }

  async ngOnInit() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
  }

  ionViewWillEnter() {
    this.getSanghList(false, '');
  }

  searchSangh() {
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.sanghList = [];
      this.pageNumber = 1;
      this.totalPage = 1;
      this.getSanghList(false, '');
    }
  }

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

  getSanghList(isFirstLoad, event) {
    this.spinnerFlag = false;
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.post(api.globalSearchSangh, {
        page: this.pageNumber,
        limit: 15,
        name: this.searchValue.trim(),
        dharma_id: this.dharma_id ? [this.dharma_id] : [],
        sampraday_id: this.sampradayData,
        latitude: this.location ? this.latitude : '',
        longitude: this.location ? this.longitude : '',
      }).then((res: any) => {
        if (isFirstLoad) { event.target.complete(); }
        if (!event) { this.sanghList = []; }
        this.totalPage = res.data.last_page;
        this.sanghList.push(...res.data.data);
        this.spinnerFlag = true;
        this.pageNumber++;
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    } else {
      event.target.complete();
      this.spinnerFlag = false;
    }
  }

  sanghProfile(sanghId: number) {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', String(sanghId)));
  }

  followSangh(event, sanghId, index) {
    event.stopPropagation();
    const params = {
      sangh_id: sanghId,
    };
    this.httpRequestService.post(api.followSangh, params).then(() => {
      this.sanghList[index].is_user_following = !this.sanghList[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() {
    const params = {
      dharma_id: this.dharma_id
    };
    this.httpRequestService.get(api.sampradayDetails, params).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.sanghList = [];
    this.pageNumber = 1;
    this.totalPage = 1;
    this.getSanghList(false, '');
    this.modalCtrl.dismiss();
  }

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

  removeLatAndLong() {
    this.longitude = '';
    this.latitude = '';
  }

  resetFilter() {
    this.location = '';
    this.longitude = '';
    this.latitude = '';
    this.dharma_id = '';
    this.sampraday_id = '';
    this.sampradayData = [];
    this.advanceSearch();
  }

  sanghRequestStatusChange(sangh, action) {
    this.alert.showLoader();
    this.httpRequestService.post(api.acceptDeclineSanghRequest, {
      sangh_id: sangh.id,
      user_id: sangh.user_id,
      status: action, // 1-accept, 2-decline/cancel
      is_commiittee: sangh.is_member,
    }).then((res: CommonResponse) => {
      this.alert.showToaster(res.message);
      sangh.sangh_member_status = (action === 1 ? 1 : 0); // 1-accept, 0-reset
    }).finally(() => {
      this.alert.hideLoader();
    });
  }

  cancelSanghRequest(sangh) {
    this.utilityService.presentConfirm(`Are you sure about cancel this request?`)
      .then(action => {
        if (action) {
          this.sanghRequestStatusChange(sangh, 2);
        }
      });
  }

  acceptDeclineSanghMember(sangh) {
    this.utilityService.presentAcceptDecline(`Please confirm`)
      .then(action => {
        if (action) {
          this.sanghRequestStatusChange(sangh, action);
        }
      });
  }

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

}
