import { NgFor, NgIf, NgSwitch, NgSwitchCase, NgTemplateOutlet } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { CommonResponse, UserData } from '@interfaces/common';
import { AlertController, IonicModule, 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-members-admin-view',
  templateUrl: './sangh-members-admin-view.page.html',
  styleUrls: ['./sangh-members-admin-view.page.scss'],
  standalone: true,
  imports: [IonicModule, NgSwitch, NgSwitchCase, NgIf, FormsModule, NgFor, NgTemplateOutlet]
})
export class SanghMembersAdminViewPage implements OnInit {
  friendRequestSegment = 'received';
  sanghId: string;
  coreMemberList = [];
  memberList = [];
  pageNumber = 1;
  totalPage = 1;
  pageNumberMember = 1;
  totalPageMember = 1;
  type: string;
  userData: UserData;

  constructor(
    private navCtrl: NavController,
    private cRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private alertController: AlertController,
    private utilityService: UtilityService,
    private stateManagementService: StateManagementService
  ) { }

  get canDeleteCoreCommittee() {
    return this.coreMemberList?.filter(member => member.sangh_member_status !== 2)?.length > 1;
  }

  async ngOnInit() {
    this.getCoreMemberList(false, '');
    this.getMemberList(false, '');
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
  }

  ionViewWillEnter() {
    this.sanghId = this.cRoute.snapshot.paramMap.get('id');
    this.type = this.cRoute.snapshot.paramMap.get('is_member');
  }

  getCoreMemberList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const apiUrl = api.sanghCommitteeMembersList.replace('{sangh_id}', String(this.cRoute.snapshot.paramMap.get('id')));
      this.httpRequestService.post(apiUrl, {
        page: this.pageNumber,
        limit: 15,
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.coreMemberList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    } else {
      event.target.complete();
    }
  }

  getMemberList(isFirstLoad, event) {
    if (this.pageNumberMember <= this.totalPageMember) {
      const apiUrl = api.sanghMembersList.replace('{sangh_id}', String(this.cRoute.snapshot.paramMap.get('id')));
      this.httpRequestService.post(apiUrl, {
        page: this.pageNumberMember,
        limit: 15,
      }).then((res: any) => {
        this.totalPageMember = res.data.last_page;
        this.memberList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumberMember++;
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    } else {
      event.target.complete();
    }
  }

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

  loadMemberData($event) {
    this.getMemberList(true, $event);
  }

  addMember(type: number) {
    if (type === 1) {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.addCommitteeMember, { id: this.sanghId }]);
    } else if (type === 2) {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.inviteMembers, { id: this.sanghId, type: 'member' }]);
    }
  }

  async updateMemberRole(user: any) {
    const alert = await this.alertController.create({
      header: 'Role Update',
      message: user.name,
      inputs: [
        {
          name: 'role',
          type: 'text',
          placeholder: 'Role',
          value: user.pivot.role,
        },
      ],
      buttons: [{
        text: 'Update',
        handler: (data) => {
          if (!data?.role) { this.alert.showToasterError('Please add role.'); return false; }
          const params = {
            sangh_id: this.cRoute.snapshot.paramMap.get('id'),
            user_id: user.id,
            role: data.role,
          };
          this.httpRequestService.post(api.updateCommitteeMember, params).then((res: any) => {
            user.pivot.role = data.role;
            this.alert.showToaster(res.message);
          }).catch((err) => {
            this.alert.showToasterError(err.error);
          });
        }
      }, {
        text: 'Cancel',
        role: 'cancel',
        cssClass: 'secondary',
      }]
    });
    await alert.present();
  }

  async deleteMember(userId: number, type: number, index: number) {
    const isYes = await this.utilityService.presentConfirm(
      userId === this.userData.id ? 'Are you sure to leave this sangh?' : 'Are you sure to delete this member from sangh?',
      'No', 'Yes', userId === this.userData.id ? 'Leave Sangh' : 'Delete Member'
    );
    if (isYes) {
      const params = {
        sangh_id: this.cRoute.snapshot.paramMap.get('id'),
        user_id: userId,
      };
      this.httpRequestService.post(api.deleteMember, params).then((res: any) => {
        if (type === 1) {
          this.coreMemberList.splice(index, 1);
        } else {
          this.memberList.splice(index, 1);
        }
        this.type = userId === this.userData.id ? '0' : this.type;
        this.alert.showToaster(res.message);
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    }
  }

  async acceptDeclineSanghMember(sangh, type, index, action) {
    const isYes = await this.utilityService.presentConfirm(`Are you sure you want to ${action} the request?`);
    if (isYes) {
      this.alert.showLoader();
      this.httpRequestService.post(api.acceptDeclineSanghRequest, {
        sangh_id: sangh.pivot.sangh_id,
        user_id: sangh.pivot.user_id,
        status: action === 'accept' ? 1 : 2, // 1-accept, 2-decline/cancel
        is_commiittee: 1,
      }).then((res: CommonResponse) => {
        this.alert.showToaster(res.message);
        if (action === 'accept') {
          sangh.sangh_member_status = 1;
        } else {
          if (type === 1) {
            this.coreMemberList.splice(index, 1);
          } else {
            this.memberList.splice(index, 1);
          }
        }
      }).finally(() => {
        this.alert.hideLoader();
      });
    }
  }

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

}
