import { NgClass, NgFor, NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AvatarPercentageComponent } from '@components/avatar-percentage/avatar-percentage.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { UserData } from '@interfaces/common';
import { AlertController, IonicModule, NavController } from '@ionic/angular';
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',
  templateUrl: './view-all.page.html',
  styleUrls: ['./view-all.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, AvatarPercentageComponent, NgClass]
})
export class ViewAllPage implements OnInit {
  santListType: string;
  santList = [];
  title: string;
  pageNumber = 1;
  totalPage = 1;
  apiRoute = '';
  isInReview = false;
  noDataFlag: boolean;
  spinnerFlag = false;
  userData: UserData;

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

  ngOnInit() {
    this.santListType = this.activatedRoute.snapshot.paramMap.get('santListType');
    if (this.santListType === '1') {
      this.title = 'In Review';
      this.apiRoute = api.inReviewSant;
      this.isInReview = true;
    } else if (this.santListType === '2') {
      this.title = 'Following';
      this.apiRoute = api.followingSant;
    } else if (this.santListType === '3') {
      this.title = 'Created By You';
      this.apiRoute = api.createdByMeSant;
    } else if (this.santListType === '4') {
      this.title = 'Suggestion';
      this.apiRoute = api.suggestionSant;
    } else if (this.santListType === '5') {
      this.title = 'Followers';
      this.apiRoute = api.followersOfSantList.replace('{sant_id}', String(this.activatedRoute.snapshot.paramMap.get('id')));
    }
    this.getSantList(false, '');
  }

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

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

  getSantList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.post(this.apiRoute, {
        page: this.pageNumber,
        limit: 15
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.noDataFlag = true;
        this.santList.push(...res.data.data);
        this.spinnerFlag = true;
        if (isFirstLoad) { event.target.complete(); }
        this.pageNumber++;
      });
    } else {
      event.target.complete();
      this.spinnerFlag = false;
    }
  }

  santProfile(sant) {
    if (this.santListType === '5') {
      if (sant.id === this.userData.id) {
        this.navController.navigateForward(Roots.page + '/' + Roots.shravakViewProfile);
      } else {
        this.navController.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id: sant.id }]);
      }
    } else if (this.santListType === '1') {
      const navOption = {
        state: {
          updatedSantId: sant.sant_id,
        },
      };
      this.navController.navigateForward(Roots.page + '/' + Roots.santViewProfile.replace(':santId', sant.sant_id), navOption);
    } else {
      this.navController.navigateForward(Roots.page + '/' + Roots.santViewProfile.replace(':santId', sant.id));
    }
  }

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

  async santBackInfo(e: Event, message: string) {
    e.stopPropagation();
    const alert = await this.alertController.create({
      message: '<ion-icon name="information-outline" class="sent-back-info-icon"></ion-icon>' +
        '<p>' + message + '</p>',
      cssClass: 'sant sent-back-info',
      mode: 'md',
      buttons: [{
        text: 'GOT IT',
        cssClass: 'si'
      }]
    });
    await alert.present();
  }
}
