import { NgClass, NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
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 { SanghData, UserData } from '@interfaces/common';
import { 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-view-all-sangh',
  templateUrl: './view-all-sangh.page.html',
  styleUrls: ['./view-all-sangh.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, NgClass]
})
export class ViewAllSanghPage implements OnInit {
  sanghListType: string;
  sanghList: Array<SanghData> = [];
  title: string;
  pageNumber = 1;
  totalPage = 1;
  apiRoute = '';
  spinnerFlag = false;
  noDataFlag: boolean;
  userData: UserData;

  constructor(
    private activatedRoute: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navController: NavController,
    private stateManagementService: StateManagementService,
    private utilityService: UtilityService
  ) { }

  async ngOnInit() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
    this.sanghListType = this.activatedRoute.snapshot.paramMap.get('sanghListType');
    if (this.sanghListType === '1') {
      this.title = 'Following';
      this.apiRoute = api.followedSanghList;
    } else if (this.sanghListType === '2') {
      this.title = 'Member of sangh';
      this.apiRoute = api.sanghList;
    } else if (this.sanghListType === '3') {
      this.title = 'Suggestion';
      this.apiRoute = api.suggestedSanghList;
    } else if (this.sanghListType === '4') {
      this.title = 'Followers';
      this.apiRoute = api.followersOfSanghList.replace('{sangh_id}', String(this.activatedRoute.snapshot.paramMap.get('id')));
    } else if (this.sanghListType === '5') {
      this.title = 'Sangh List';
      this.apiRoute = api.getUserSanghList;
    } else if (this.sanghListType === '6') {
      this.title = 'In Review Sangh';
      this.apiRoute = api.inReviewUserSanghList;
    }
    this.getSanghList(false, '', this.sanghListType);
  }

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

  getSanghList(isFirstLoad, event, type?: string) {
    if (this.pageNumber <= this.totalPage) {
      let params: any = {
        page: this.pageNumber,
        limit: 15
      };
      if (type === '5') {
        params = {
          ...params,
          user_id: this.activatedRoute.snapshot.paramMap.get('id') ? String(this.activatedRoute.snapshot.paramMap.get('id')) : '',
        };
      }
      this.httpRequestService.post(this.apiRoute, params).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.noDataFlag = true;
        this.sanghList.push(...res.data.data);
        this.spinnerFlag = true;
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      event.target.complete();
      this.noDataFlag = false;
    }
  }

  async deleteSangh(id: number, index: number) {
    const isYes = await this.utilityService.presentConfirm(
      `Are you sure want to delete Sangh?`,
      'No', 'Yes'
    );
    if (isYes) {
      this.httpRequestService.delete(api.deleteSangh + id).then(() => {
        this.alert.showToaster('Sangh deleted successfully');
        this.sanghList.splice(index, 1);
      });
    }
  }


  sanghProfile(sanghId) {
    if (this.sanghListType !== '4') {
      this.navController.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', String(sanghId)));
    } else if (this.sanghListType === '4') {
      if (sanghId === this.userData.id) {
        this.navController.navigateForward(Roots.page + '/' + Roots.shravakViewProfile);
      } else {
        this.navController.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id: sanghId }]);
      }
    }
  }

  async followSangh(event, sanghData, index) {
    if (sanghData.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.followSangh, {
          sangh_id: sanghData.id,
        });
        this.sanghList[index].is_user_following = !this.sanghList[index].is_user_following;
        if (this.sanghList[index].is_user_following === false) {
          this.sanghList.splice(index, 1);
        }
      }
    } else {
      event.stopPropagation();
      const params = {
        sangh_id: sanghData.id,
      };
      this.httpRequestService.post(api.followSangh, params).then(() => {
        this.sanghList[index].is_user_following = !this.sanghList[index].is_user_following;
        if (this.sanghList[index].is_user_following === false) {
          this.sanghList.splice(index, 1);
        }
      });
    }
  }

  joinSangh(sangh: SanghData) {
    if (sangh.is_requested === true) {
      this.acceptDeclineSanghMember(sangh);
    } else {
      const params = {
        sangh_id: sangh.id,
        user_id: [this.userData.id],
        is_join: 1,
      };
      this.httpRequestService.post(api.addMemberForSangh, params).then((res: any) => {
        sangh.is_requested = true;
        this.alert.showToaster(res.message);
      }).catch((err) => {
        this.alert.showToasterError(err.error);
      });
    }
  }

  async acceptDeclineSanghMember(sangh: SanghData) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure about cancel this request?',
      'No', 'Yes', 'Cancel Request'
    );
    if (isYes) {
      const params = {
        sangh_id: sangh.id,
        user_id: this.userData.id,
        status: 2,
      };
      this.httpRequestService.post(api.acceptDeclineSanghRequest, params).then((res: any) => {
        sangh.is_requested = false;
        this.alert.showToaster(res.message);
      });
    }
  }

}
