import { NgFor, NgIf } from '@angular/common';
import { Component } from '@angular/core';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-invitations',
  templateUrl: './invitations.page.html',
  styleUrls: ['./invitations.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor]
})
export class InvitationsPage {
  invitationList = [];
  invitationPageNumber = 1;
  invitationTotalPage = 1;
  invitationTotalCount: number;
  noDataFlag: boolean;
  spinnerFlag = false;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private utilityService: UtilityService,
    private navCtrl: NavController
  ) { }

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

  getInvitationList(isFirstLoad, event) {
    if (this.invitationPageNumber <= this.invitationTotalPage) {
      const params = {
        page: this.invitationPageNumber,
        limit: 15,
      };
      this.httpRequestService.get(api.getSanghInvitationsList, params).then((res: any) => {
        this.invitationTotalPage = res.data.last_page;
        this.invitationTotalCount = res.data.total;
        this.noDataFlag = true;
        this.invitationList.push(...res.data.data);
        this.spinnerFlag = true;
        if (isFirstLoad) { event.target.complete(); }
        this.invitationPageNumber++;
      });
    } else {
      event.target.complete();
      this.spinnerFlag = false;
    }
  }

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

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

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

  async acceptDeclineSanghMember(data: any, status: number, index: number) {

    const acceptDeclineSanghMember = () => {
      const params = {
        sangh_id: data.extra_fields.sangh_id,
        user_id: data.extra_fields.from_id,
        status,
        is_commiittee: data.type === 'UserSentMemberRequest' ? 1 : 0,
      };
      this.httpRequestService.post(api.acceptDeclineSanghRequest, params).then((res: any) => {
        this.invitationList.splice(index, 1);
        this.alert.showToaster(res.message);
      });
    };

    if (status === 2) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure about decline this request?',
        'No', 'Yes', 'Decline'
      );
      if (isYes) { acceptDeclineSanghMember(); }
    } else {
      acceptDeclineSanghMember();
    }
  }

}
