import { NgFor, NgIf, NgSwitch, NgSwitchCase } from '@angular/common';
import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { FooterComponent } from '@components/footer/footer.component';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, FriendList, RequestUserList } from '@interfaces/common';
import { IonicModule, NavController, PopoverController } 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';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-friend-request',
  templateUrl: './friend-request.page.html',
  styleUrls: ['./friend-request.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, FormsModule, NgSwitch, NgSwitchCase, NgFor, FooterComponent]
})
export class FriendRequestPage implements OnInit, OnDestroy {
  requestList: Array<RequestUserList> = [];
  requestSentList: Array<RequestUserList> = [];
  friendList: Array<FriendList> = [];
  friendRequestSegment = 'friend';
  pageNumber = 1;
  totalPage = 1;
  totalCount: number;
  spinnerFlag = false;
  pageNumberRequestList = 1;
  totalPageRequestList = 1;
  totalCountRequestList: number;
  noRequestListFlag: boolean;
  pageNumberSentList = 1;
  totalPageSentList = 1;
  totalCountSentList: number;
  noSentListFlag: boolean;
  suggestedFriendList = [];
  $subscription: Subscription;
  hasNewPendingRequest = 0;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private ngZone: NgZone,
    private utilityService: UtilityService,
    private activatedRoute: ActivatedRoute,
    private popoverCtrl: PopoverController,
    private stateManagementService: StateManagementService,
    private change: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.friendRequestSegment = this.activatedRoute?.snapshot?.paramMap?.get('friendRequestSegment') || 'friend';
    this.$subscription = this.stateManagementService.pushNotyObservable.subscribe(res => {
      this.hasNewPendingRequest = res.pending_friend_request;
      this.change.detectChanges();
    });
  }

  ionViewWillEnter() {
    this.getSuggestionFriendList();
    this.getFriendList(false, '');
  }

  changeTab() {
    if (this.friendRequestSegment === 'received') {
      this.stateManagementService.generalData.pending_friend_request = 0;
      this.stateManagementService.pushNotyObservable.next(this.stateManagementService.generalData);
      this.getRequestList(false, '');
    } else if (this.friendRequestSegment === 'sent') {
      this.getRequestSentList(false, '');
    }
  }

  getSuggestionFriendList() {
    const params = {
      page: 1,
      limit: 10
    };
    this.httpRequestService.post(api.suggestionShravakList, params).then((res: any) => {
      if (res.data && res.data.data) {
        this.suggestedFriendList = res.data.data;
        this.suggestedFriendList.forEach(el => el.isLoading = false);
      }
    });
  }

  getFriendList(isFirstLoad, event) {
    this.spinnerFlag = false;
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.get(api.myFriendList, {
        page: this.pageNumber,
        limit: 15
      }).then((res: CommonResponse) => {
        this.totalPage = res.data.last_page;
        this.totalCount = res.data.total;
        this.friendList.push(...res.data.data);
        this.spinnerFlag = true;
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      if (event) {
        event.target.complete();
      }
      this.spinnerFlag = true;
    }
  }

  loadFriendListData($event) {
    this.getFriendList(true, $event);
  }

  getRequestList(isFirstLoad, event) {
    if (this.pageNumberRequestList <= this.totalPageRequestList) {
      this.httpRequestService.get(api.myConnectionRequestList, {
        page: this.pageNumberRequestList,
        limit: 15
      }).then((res: CommonResponse) => {
        this.totalPageRequestList = res.data.last_page;
        this.noRequestListFlag = true;
        this.totalCountRequestList = res.data.total;
        this.requestList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumberRequestList++;
      });
    } else {
      if (event) { event.target.complete(); }
    }
  }

  loadRequestListData($event) {
    this.getRequestList(true, $event);
  }

  getRequestSentList(isFirstLoad, event) {
    if (this.pageNumberSentList <= this.totalPageSentList) {
      this.httpRequestService.get(api.myConnectionRequestSentList, {
        page: this.pageNumberSentList,
        limit: 15
      }).then((res: CommonResponse) => {
        this.totalPageSentList = res.data.last_page;
        this.noSentListFlag = true;
        this.totalCountSentList = res.data.total;
        this.requestSentList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumberSentList++;
      });
    } else {
      if (event) { event.target.complete(); }
    }
  }

  loadRequestSentListData($event) {
    this.getRequestSentList(true, $event);
  }

  sendConnectionRequest(id: number, actionStatus: number, index: number) {
    this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: id, status: actionStatus })
      .then((res: CommonResponse) => {
        this.requestList.splice(index, 1);
        this.alert.showToaster(res.message);
      });
  }

  viewPublicProfile(id: number) {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id }]);
  }

  moveToMessage(data: FriendList) {
    this.popoverCtrl.dismiss().then(() => {
      this.ngZone.run(() => this.navCtrl.navigateForward([Roots.page + '/' + Roots.messageChat, {
        userId: data.id,
        name: data.name
      }])).then();
    });
  }

  async confirmationAlert(data: FriendList, index: number) {
    const message = 'Are you sure you want to remove User ' + data.name + ' from your connection?';
    const isYes = await this.utilityService.presentConfirm(message);
    if (isYes) {
      this.popoverCtrl.dismiss().then(() => {
        this.httpRequestService.post(api.connectionRequestStatusUpdate, { receiver_id: data.id, status: 2 })
          .then((res: CommonResponse) => {
            this.friendList.splice(index, 1);
            this.alert.showToaster(res.message);
          });
      });
    }
  }

  moveToFriendsSuggestionsViewAll() {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.friendsSuggestionsViewAll);
  }

  sendFriendRequest(id: number, data: any, index: number) {
    data.isLoading = true;
    this.httpRequestService.post(api.connectionRequestSend, { receiver_id: id })
      .then((res: CommonResponse) => {
        data.is_friends = 2;
        this.suggestedFriendList.splice(index, 1);
        data.isLoading = false;
        this.alert.showToaster(res.message);
      }).catch(() => {
        data.isLoading = false;
      });
  }

  searchFriend() {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.searchFriend);
  }

  ngOnDestroy() {
    this.$subscription?.unsubscribe();
  }
}
