import { NgFor, NgIf, NgSwitch, NgSwitchCase } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { App } from '@capacitor/app';
import { AvatarPercentageComponent } from '@components/avatar-percentage/avatar-percentage.component';
import { FooterComponent } from '@components/footer/footer.component';
import { MessageNotificationBadgeComponent } from '@components/message-notification-badge/message-notification-badge.component';
import { PostComponent } from '@components/post/post.component';
import { SantPostComponent } from '@components/sant-post/sant-post.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { Dharma, Jaati, PostList, SantActivityList, UserData } from '@interfaces/common';
import { IonicModule, NavController, Platform, PopoverController } from '@ionic/angular';
import { CertificateBannerComponent } from '@pages/common/certificate-banner/certificate-banner.component';
import { AlertService } from '@services/alert.service';
import { CameraGalleryService } from '@services/camera-gallery.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-shravak-feeds',
  templateUrl: './shravak-feeds.page.html',
  styleUrls: ['./shravak-feeds.page.scss'],
  standalone: true,
  imports: [IonicModule, AvatarPercentageComponent, CertificateBannerComponent, MessageNotificationBadgeComponent, FormsModule, NgSwitch, NgSwitchCase, NgIf, NgFor,
    PostComponent, SantPostComponent, FooterComponent]
})
export class ShravakFeedsPage implements OnInit, OnDestroy {
  feedSegment = 'shravak';
  userData: UserData;
  dharmaDetails: Array<Dharma> = [];
  jaatiDetails: Array<Jaati> = [];
  pageNumber = 1;
  totalPage = 1;
  totalPostCount: number;
  santPageNumber = 1;
  santTotalPage = 1;
  santTotalPostCount: number;
  sanghPageNumber = 1;
  sanghTotalPage = 1;
  sanghTotalPostCount: number;
  postList: Array<PostList> = [];
  santPostList: Array<SantActivityList> = [];
  sanghPostList: Array<PostList> = [];
  avatar: string;
  noDataFlag: boolean;
  spinnerFlag: boolean;
  profileCompletionPercentage = 0;
  $subscription: Subscription;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private popoverCtrl: PopoverController,
    private platform: Platform,
    private router: Router,
    private cameraGalleryService: CameraGalleryService,
  ) { }

  ngOnInit() {
    if (this.stateManagementService.dharmaDetails.length > 0) {
      this.dharmaDetails = this.stateManagementService.dharmaDetails;
    } else {
      this.getDharmaDetails();
    }
    if (this.stateManagementService.jaatiDetails.length > 0) {
      this.jaatiDetails = this.stateManagementService.jaatiDetails;
    } else {
      this.getJaatiList();
    }
    this.$subscription = this.stateManagementService.pushNotyObservable.subscribe(res => {
      this.profileCompletionPercentage = res.profile_completion_percentage;
    });
    if (this.router?.url?.includes('sangh')) {
      this.feedSegment = 'sangh';
    }
    this.noDataFlag = this.stateManagementService.noDataFlag;
  }

  async ionViewWillEnter() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
    this.avatar = this.userData.avatar;
    this.totalPage = 1;
    this.pageNumber = 1;
    this.santPageNumber = 1;
    this.santTotalPage = 1;
    this.sanghPageNumber = 1;
    this.sanghTotalPage = 1;
    this.postList = [];
    this.santPostList = [];
    this.sanghPostList = [];
    this.getPostList(false, '', 'post');
    this.getPostList(false, '', 'sant');
    this.getPostList(false, '', 'sangh');
  }

  ionViewDidEnter() {

    // --- check router path and close the app otherwise navigate to back
    const checkAndCloseOrPop = () => {
      if (this.router.url === ('/' + Roots.page + '/' + Roots.shravakFeeds)) {
        App.exitApp();
      } else {
        this.navCtrl.pop();
      }
    };

    if (this.platform.is('android')) {
      this.platform.ready().then(() => {
        this.platform.backButton.subscribeWithPriority(0, async () => {
          if (this.popoverCtrl.getTop()) {
            const modal = await this.popoverCtrl.getTop();
            if (modal) {
              this.popoverCtrl.dismiss();
              return;
            } else {
              checkAndCloseOrPop();
            }
          } else {
            checkAndCloseOrPop();
          }
        });

      });
    }
  }

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

  getDharmaDetails() {
    this.httpRequestService.get(api.dharmaDetails).then((res: any) => {
      this.dharmaDetails = res.data;
      this.stateManagementService.dharmaDetails = res.data;
    });
  }

  getJaatiList() {
    this.httpRequestService.get(api.jaatiList).then((res: any) => {
      this.jaatiDetails = res.data;
      this.stateManagementService.jaatiDetails = res.data;
    });
  }

  loadData($event, feedType: string) {
    this.getPostList(true, $event, feedType);
  }

  // --- fetch post list based on your feed type
  getPostList(isFirstLoad, event, feedType) {
    const assignDataAndPostProcess = (res: any) => {
      switch (feedType) {
        case 'post':
          this.totalPage = res.data.last_page;
          this.stateManagementService.noDataFlag = res.data.data.length > 0;
          this.noDataFlag = res.data.data.length > 0;
          this.spinnerFlag = true;
          this.totalPostCount = res.data.total;
          this.postList.push(...res.data.data);
          if (isFirstLoad) { event.target.complete(); }
          this.pageNumber = res.data.current_page + 1;
          break;
        case 'sant':
          this.santTotalPage = res.data.last_page;
          this.santTotalPostCount = res.data.total;
          this.santPostList.push(...res.data.data);
          if (isFirstLoad) { event.target.complete(); }
          this.santPageNumber = res.data.current_page + 1;
          break;
        case 'sangh':
          this.sanghTotalPage = res.data.last_page;
          this.sanghTotalPostCount = res.data.total;
          this.sanghPostList.push(...res.data.data);
          if (isFirstLoad) { event.target.complete(); }
          this.sanghPageNumber = res.data.current_page + 1;
          break;
        default:
          break;
      }
    };

    if ((feedType === 'post' && this.pageNumber <= this.totalPage) ||
      (feedType === 'sant' && this.santPageNumber <= this.santTotalPage) ||
      (feedType === 'sangh' && this.sanghPageNumber <= this.sanghTotalPage)) {
      if (feedType === 'post') {
        this.httpRequestService.get(api.postList, {
          page: this.pageNumber,
          limit: 5
        }).then((res: any) => {
          assignDataAndPostProcess(res);
        });
      } else if (feedType === 'sant' || feedType === 'sangh') {
        const url = feedType === 'sant' ? api.santActivityList : api.sanghPostList;
        this.httpRequestService.post(url, {
          page: feedType === 'sant' ? this.santPageNumber : this.sanghPageNumber,
          limit: 5
        }).then((res: any) => {
          assignDataAndPostProcess(res);
        });
      }
    } else {
      event.target.complete();
      this.spinnerFlag = false;
    }
  }

  selectImages() {
    this.cameraGalleryService.selectMultipleImage(512, 512, false).then((imageData: Array<{ imgString: string; itemImage: Blob }>) => {
      if (imageData && imageData.length > 0) {
        imageData.forEach((image) => {
          const imageSize = image.itemImage.size / 1048576; // in MB
          if (((imageSize <= 10) && (this.stateManagementService.imageArray.length < 3))) {
            this.stateManagementService.imageArray.push(image);
          }
          if ((this.stateManagementService.imageArray.length) >= 3) {
            this.alert.showToaster('Max 3 image can be uploaded');
            return;
          }
          if (imageSize > 10) {
            this.alert.showToaster('Image size must be less than 10Mb');
          }
        });
        this.moveToCreatePost();
      }
    });
  }

  moveToCreatePost() {
    const navOption = {
      state: {
        isUpdate: false,
        fromFeed: true,
        redirectTo: 'page/shravak-feeds',
        type: 1,
        type_id: this.userData.id,
        userAvatar: this.userData?.avatar,
        userName: this.userData?.name
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
  }

  async onRefresh(event) {
    switch (this.feedSegment) {
      case 'shravak':
        this.pageNumber = 1;
        this.totalPage = 1;
        this.postList = [];
        await this.getPostList(false, '', 'post');
        break;
      case 'sant':
        this.santPageNumber = 1;
        this.santTotalPage = 1;
        this.santPostList = [];
        await this.getPostList(false, '', 'sant');
        break;
      case 'sangh':
        this.sanghPageNumber = 1;
        this.sanghTotalPage = 1;
        this.sanghPostList = [];
        await this.getPostList(false, '', 'sangh');
        break;
    }
    await event.target.complete();
  }

  redirect(type: string) {
    this.navCtrl.navigateRoot([`${Roots.page}/${type === 'sant' ? Roots.createNewSant : Roots.createNewSangh}`]);
  }

  globalSearch() {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.globalSearch], {
      state: {
        activeTab: 'shravak'
      }
    });
  }

  goToCertificate() {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.certificate]);
  }

  goToSangh() {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.createNewSangh]);
  }

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