import { DOCUMENT, DecimalPipe, NgClass, NgFor, NgIf, NgSwitch, NgSwitchCase } from '@angular/common';
import { Component, ElementRef, Inject, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';

import { AvatarPercentageComponent } from '@components/avatar-percentage/avatar-percentage.component';
import { IonicSelectableComponent } from '@components/ionic-selectable/ionic-selectable.component';
import { JoinSanghButtonComponent } from '@components/join-sangh-button/join-sangh-button.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import {
  CommonResponse, Dharma, GlobalSearchDataSangh, GlobalSearchDataSant,
  GlobalSearchDataShravak,
  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-global-search',
  templateUrl: './global-search.page.html',
  styleUrls: ['./global-search.page.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, NgSwitch, NgSwitchCase, NgIf, NgFor, NgClass,
    AvatarPercentageComponent, IonicSelectableComponent, DecimalPipe, JoinSanghButtonComponent]
})
export class GlobalSearchPage implements OnInit, OnDestroy {
  @ViewChild('personalLocation') personalLocation: ElementRef;
  @ViewChild('currentLocation') currentLocation: ElementRef;
  @ViewChild('nativeLocation') nativeLocation: ElementRef;
  searchSegment: 'sant' | 'shravak' | 'sangh' = 'sant';
  searchedShravakData: Array<GlobalSearchDataShravak> = [];
  searchedSantData: Array<GlobalSearchDataSant> = [];
  searchedSanghData: Array<GlobalSearchDataSangh> = [];
  pageNumberShravak = 1;
  totalPageShravak = 1;
  pageNumberSant = 1;
  totalPageSant = 1;
  pageNumberSangh = 1;
  totalPageSangh = 1;
  totalCountShravak: number;
  totalCountSangh: number;
  totalCountSant: number;
  searchValue = '';
  noDataFlagShravak: boolean;
  noDataFlagSant: boolean;
  noDataFlagSangh: boolean;
  userData: UserData;
  sampradayDetails: Array<Sampraday> = [];
  dharmaDetails: Array<Dharma> = [];
  dharma_id: any;
  sampraday_id: any;
  gender_id: any;
  location: any;
  longitude = '';
  latitude = '';
  currentLongitude = '';
  currentLatitude = '';
  nativeLongitude = '';
  nativeLatitude = '';
  current_location: any;
  native_location: any;
  sampradayData = [];
  seeMoreShravak = false;
  seeMoreSangh = false;
  seeMoreSant = false;
  prevValue: string;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private navCtrl: NavController,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private stateManagementService: StateManagementService,
    private modalCtrl: ModalController,
    private renderer: Renderer2,
    private utilityService: UtilityService,
    private router: Router
  ) { }

  get tabRecordCount() {
    return this.searchValue.trim() ?
      this.searchSegment === 'shravak' ? this.totalCountShravak - 3 :
        this.searchSegment === 'sangh' ? this.totalCountSangh - 3 :
          this.searchSegment === 'sant' ? this.totalCountSant - 3 : 0
      : 0;
  }

  get shravakAll() {
    return !this.seeMoreShravak && this.tabRecordCount > 0 ? this.searchedShravakData.slice(0, 3) : this.searchedShravakData;
  }

  get sanghAll() {
    return !this.seeMoreSangh && this.tabRecordCount > 0 ? this.searchedSanghData.slice(0, 3) : this.searchedSanghData;
  }

  get santAll() {
    return !this.seeMoreSant && this.tabRecordCount > 0 ? this.searchedSantData.slice(0, 3) : this.searchedSantData;
  }

  ngOnInit(): void {
    if (this.router.getCurrentNavigation().extras.state?.activeTab) {
      this.searchSegment = this.router.getCurrentNavigation().extras.state?.activeTab;
    }
    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();
    }
  }

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

  globalSearchShravak(isFirstLoad, event) {
    this.noDataFlagShravak = false;
    if (this.pageNumberShravak <= this.totalPageShravak) {
      this.httpRequestService.post(api.globalSearchShravak, {
        page: this.pageNumberShravak,
        limit: 15,
        name: this.searchValue.trim(),
        longitude: this.current_location ? this.currentLongitude : '',
        latitude: this.current_location ? this.currentLatitude : '',
        native_longitude: this.native_location ? this.nativeLongitude : '',
        native_latitude: this.native_location ? this.nativeLatitude : '',
        gender_id: this.gender_id ? [this.gender_id] : []
      }).then((res: any) => {
        if (isFirstLoad) { event.target.complete(); }
        if (!event) {
          this.seeMoreShravak = false;
          this.searchedShravakData = [];
        }
        this.searchedShravakData.push(...res.data.data);
        this.totalPageShravak = res.data.last_page;
        this.noDataFlagShravak = true;
        this.totalCountShravak = res.data.total;
        this.pageNumberShravak++;
      });
    } else {
      if (event) { event.target.complete(); }
      this.noDataFlagShravak = true;
    }
  }

  globalSearchSangh(isFirstLoad, event) {
    this.noDataFlagSangh = false;
    if (this.pageNumberSangh <= this.totalPageSangh) {
      this.httpRequestService.post(api.globalSearchSangh, {
        page: this.pageNumberSangh,
        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.seeMoreSangh = false;
          this.searchedSanghData = [];
        }
        this.searchedSanghData.push(...res.data.data);
        this.totalPageSangh = res.data.last_page;
        this.noDataFlagSangh = true;
        this.totalCountSangh = res.data.total;
        this.pageNumberSangh++;
      });
    } else {
      if (event) { event.target.complete(); }
      this.noDataFlagSangh = true;
    }
  }

  globalSearchSant(isFirstLoad, event) {
    this.noDataFlagSant = false;
    if (this.pageNumberSant <= this.totalPageSant) {
      this.httpRequestService.post(api.globalSearchSant, {
        page: this.pageNumberSant,
        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.current_location ? this.currentLongitude : '',
        latitude: this.current_location ? this.currentLatitude : '',
      }).then((res: any) => {
        if (isFirstLoad) { event.target.complete(); }
        if (!event) {
          this.seeMoreSant = false;
          this.searchedSantData = [];
        }
        this.searchedSantData.push(...res.data.data);
        this.totalPageSant = res.data.last_page;
        this.noDataFlagSant = true;
        this.totalCountSant = res.data.total;
        this.pageNumberSant++;
      });
    } else {
      if (event) { event.target.complete(); }
      this.noDataFlagSant = true;
    }
  }

  loadShravakData($event) {
    this.globalSearchShravak(true, $event);
  }

  loadSanghData($event) {
    this.globalSearchSangh(true, $event);
  }

  loadSantData($event) {
    this.globalSearchSant(true, $event);
  }

  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;
    });
  }

  viewPublicProfile(id: number, type: string) {
    if (type === 'user') {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id }]);
    } else if (type === 'sant') {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.santViewProfile, { santId: id }]);
    } else if (type === 'sangh') {
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', String(id)));
    }
  }

  sendConnectionRequest(id: number, data: GlobalSearchDataShravak) {
    this.httpRequestService.post(api.connectionRequestSend, { receiver_id: id })
      .then((res: CommonResponse) => {
        data.is_friends = 2;
        this.alert.showToaster(res.message);
      });
  }

  acceptDeclineRequest(id: number, data: GlobalSearchDataShravak, status: number, type?: number) {
    if (status === 1) {
      this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: id, status })
        .then((res: CommonResponse) => {
          data.is_friends = 1;
          this.alert.showToaster(res.message);
        });
    } else {
      this.confirmationAlert(id, data, type);
    }
  }

  async confirmationAlert(id, data: GlobalSearchDataShravak, type: number) {
    const message =
      type === 1 ? `Are you sure you want to remove User ${data.name} from your connection?` :
        type === 2 ? ` 'Are you sure about to cancel this request?` :
          '';
    const isYes = await this.utilityService.presentConfirm(message);
    if (isYes) {
      const res: CommonResponse = await this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: id, status: 2 });
      data.is_friends = 0;
      this.alert.showToaster(res.message);
    }
  }

  async followSant(id: number, data: GlobalSearchDataSant, event) {
    const params = {
      sant_id: id,
    };
    if (data.is_user_following) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure you want to unfollow?',
        'No', 'Yes', 'Unfollow'
      );
      if (isYes) {
        event.stopPropagation();
        await this.httpRequestService.post(api.followSant, params);
        data.is_user_following = !data.is_user_following;
      }
    } else {
      event.stopPropagation();
      await this.httpRequestService.post(api.followSant, params);
      data.is_user_following = !data.is_user_following;
    }
  }

  searchName($event) {
    this.searchValue = $event.detail.value;
    const isSameStr = this.utilityService.isSameStr(this.searchValue, this.prevValue);
    this.prevValue = this.searchValue;
    if (!isSameStr) {
      this.advanceSearch();
    }
  }


  onDharmChange() {
    this.sampraday_id = [];
    if (this.searchSegment !== 'shravak') {
      this.getSampradayDetails();
    }
  }

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

  async advanceSearch() {
    if (this.searchSegment === 'shravak') {
      this.searchedShravakData = [];
      this.pageNumberShravak = 1;
      this.totalPageShravak = 1;
      this.globalSearchShravak(false, '');
    } else if (this.searchSegment === 'sangh') {
      this.searchedSanghData = [];
      this.pageNumberSangh = 1;
      this.totalPageSangh = 1;
      this.globalSearchSangh(false, '');
    } else if (this.searchSegment === 'sant') {
      this.searchedSantData = [];
      this.pageNumberSant = 1;
      this.totalPageSant = 1;
      this.globalSearchSant(false, '');
    }
    const isOpen = await this.modalCtrl.getTop();
    if (isOpen) { this.modalCtrl.dismiss(); }
  }

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

  initAutocompleteNative(): void {
    this.utilityService.createAutocomplete(this.nativeLocation.nativeElement, []).subscribe((details) => {
      this.native_location = this.nativeLocation.nativeElement.value;
      this.nativeLongitude = details.geometry.location.lng();
      this.nativeLatitude = details.geometry.location.lat();
    });
  }

  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();
    });
  }

  changeSegment(event) {
    this.resetSantFilter();
    this.resetSanghFilter();
    this.resetShravakFilter();
    this.sampradayData = [];
    this.renderer.removeClass(this.document.body, 'auto-location');
    this.renderer.removeClass(this.document.body, 'search-selectable');
    if (event.detail.value === 'sant') {
      this.searchedSantData = [];
      this.globalSearchSant(false, '');
      this.renderer.addClass(this.document.body, 'search-selectable');
    } else if (event.detail.value === 'sangh') {
      this.searchedSanghData = [];
      this.globalSearchSangh(false, '');
      this.renderer.addClass(this.document.body, 'auto-location');
    } else if (event.detail.value === 'shravak') {
      this.searchedShravakData = [];
      this.globalSearchShravak(false, '');
    }
  }

  // --- Reset sant filter
  resetSantFilter() {
    this.pageNumberSant = this.totalPageSant = 1;
    this.dharma_id = this.sampraday_id = this.gender_id = this.current_location = '';
    this.sampradayData = [];
  }

  // --- reset sangh filter
  resetSanghFilter() {
    this.pageNumberSangh = this.totalPageSangh = 1;
    this.location = this.longitude = this.latitude = this.dharma_id = this.sampraday_id = '';
    this.sampradayData = [];
  }

  resetShravakFilter() {
    this.current_location = this.currentLatitude = this.currentLongitude = this.native_location = this.nativeLatitude =
      this.nativeLongitude = this.gender_id = '';
    this.pageNumberShravak = this.totalPageShravak = 1;
  }

  resetFilter() {
    if (this.searchSegment === 'sant') {
      this.resetSantFilter();
      this.searchedSantData = [];
      this.globalSearchSant(false, '');
    } else if (this.searchSegment === 'sangh') {
      this.resetSanghFilter();
      this.searchedSanghData = [];
      this.globalSearchSangh(false, '');
    } else if (this.searchSegment === 'shravak') {
      this.resetShravakFilter();
      this.searchedShravakData = [];
      this.globalSearchShravak(false, '');
    }
  }

  acceptDecline(sangh) {
    this.utilityService.presentAcceptDecline(`Please confirm`)
      .then(action => {
        if (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 === 0 ? 0 : 1,
          }).then((res: CommonResponse) => {
            this.alert.showToaster(res.message);
            sangh.sangh_member_status = (action === 1 ? 1 : 0); // 1-accept, 0-reset
          }).finally(() => {
            this.alert.hideLoader();
          });
        }
      });
  }

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

}
