import { NgFor, NgIf } from '@angular/common';
import { Component } from '@angular/core';
import { Share, ShareOptions } from '@capacitor/share';
import { PostComponent } from '@components/post/post.component';
import { ProfileCompleteIndicatorComponent } from '@components/profile-complete-indicator/profile-complete-indicator.component';
import { api } from '@enums/api.enum';
import { GJainStorage } from '@enums/gjain-storage.enum';
import { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { CommonResponse, ProfileData, ProfileResponse } from '@interfaces/common';
import { ActionSheetController, IonicModule, NavController, PopoverController } from '@ionic/angular';
import { SafeUrlPipe } from '@pipes/safe-url.pipe';
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 { UtilityService } from '@services/utility.service';

@Component({
  selector: 'app-shravak-view-profile',
  templateUrl: './shravak-view-profile.page.html',
  styleUrls: ['./shravak-view-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, ProfileCompleteIndicatorComponent, NgFor, PostComponent, SafeUrlPipe]
})
export class ShravakViewProfilePage {
  userProfileData: ProfileData;
  postList = [];
  pageNumber = 1;
  totalPage = 1;
  totalCount: number;
  photo: any;
  popover: HTMLIonPopoverElement = null;
  profileCompletionPercentage = 0;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navController: NavController,
    private stateManagementService: StateManagementService,
    private popoverCtrl: PopoverController,
    public actionSheetCtrl: ActionSheetController,
    private cameraGalleryService: CameraGalleryService,
    public utilityService: UtilityService
  ) { }

  ionViewWillEnter() {
    this.postList = [];
    this.getProfileInfo();
    this.pageNumber = 1;
    this.totalPage = 1;
    this.getPostList(false, '');
  }

  getProfileInfo() {
    this.httpRequestService.get(api.shravakProfile).then(async (res: ProfileResponse) => {
      this.userProfileData = res.data;
      this.profileCompletionPercentage = +this.userProfileData?.profile_statistics?.profile_completion_percentage;

      this.stateManagementService.userProfileData = res.data;
      this.stateManagementService.storage.set(GJainStorage.profileData, res.data);

      const userData = await this.stateManagementService.storage.get(GJainStorage.userData);
      userData.avatar = res.data.avatar;
      this.stateManagementService.storage.set(GJainStorage.userData, userData);

      this.stateManagementService.generalData.profile_completion_percentage = this.profileCompletionPercentage;
      this.stateManagementService.pushNotyObservable.next(this.stateManagementService.generalData);
    });
  }

  getPostList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      this.httpRequestService.get(api.userPostList, {
        page: this.pageNumber,
        limit: 5,
      }).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.pageNumber = res.data.current_page + 1;
        this.totalCount = res.data.total;
        this.postList.push(...res.data.data);
        if (isFirstLoad) { event.target.complete(); }
      });
    } else {
      event.target.complete();
    }
  }

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

  async updatePost(postInfo) {
    await this.popoverCtrl.dismiss().then(() => {
      const navOption = {
        state: {
          postData: postInfo,
          isUpdate: true,
          redirectTo: Roots.page + '/' + Roots.shravakViewProfile,
          type: postInfo.type ? postInfo.type : 1,
          type_id: postInfo.type_id ? postInfo.type_id : postInfo.created_by.id,
          userAvatar: this.userProfileData?.avatar,
          userName: this.userProfileData?.name
        },
      };
      this.navController.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
      this.popoverCtrl.dismiss();
    });
  }

  async deletePost(postId) {
    await this.popoverCtrl.dismiss().then(() => {
      this.presentAlert(postId);
      this.popoverCtrl.dismiss();
    });
  }

  async presentAlert(postId) {
    const isYes = await this.utilityService.presentConfirm(
      'Are you sure you want to delete this post?',
      'No', 'Yes', 'Delete post'
    );
    if (isYes) {
      this.httpRequestService.delete(api.deletePost + '/' + postId).then((res: any) => {
        this.postList = [];
        this.pageNumber = 1;
        this.getPostList(false, '');
        this.alert.showToaster(res.message);
      });
    }
  }


  goToAboutInfo(from?: string) {
    const navOption = {
      state: {
        userData: this.userProfileData,
        from: from ? from : ''
      },
    };
    this.navController.navigateForward(Roots.page + '/' + Roots.shravakAbout, navOption);
  }

  moveToCreatePost() {
    const navOption = {
      state: {
        isUpdate: false,
        redirectTo: Roots.page + '/' + Roots.shravakViewProfile,
        type: 1,
        type_id: this.userProfileData.id,
        userAvatar: this.userProfileData?.avatar,
        userName: this.userProfileData?.name
      },
    };
    this.navController.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
  }


  async shareProfile() {
    const options: ShareOptions = {
      url: `${environment.siteUrl}/page/shravak-other-profile/${this.userProfileData.id}`,
    };
    await Share.share(options);
  }

  async selectProfileImage() {
    this.cameraGalleryService.selectImage(512, 512, true).then((imageData: { imgString: string; itemImage: Blob }) => {
      if (imageData) {
        const imageSize = imageData.itemImage.size / 1048576; // in MB
        if (imageSize <= 10) {
          const formdata = new FormData();
          formdata.append('avatar', imageData.itemImage);
          this.httpRequestService.post(api.updateShravakProfile, formdata).then(async (res: CommonResponse) => {
            this.userProfileData.avatar = imageData.imgString;
            this.getProfileInfo();
            this.alert.hideLoader();
            this.alert.showToaster(res.message);
          });
        }
        if (imageSize > 10) {
          this.alert.showToaster('Image size must be less than 10Mb');
        }
      }
    });
  }

  goToFriendList() {
    if (this.userProfileData && this.userProfileData.friend_count > 0) {
      this.navController.navigateForward([Roots.page + '/' + Roots.friendRequest]);
    }
  }

  viewAllSangh(sanghListType) {
    if (this.userProfileData && this.userProfileData.sangh_member_count > 0) {
      this.navController.navigateForward(`page/view-all-sangh/${sanghListType}`);
    }
  }

  address(type: string) {
    if (type === 'native') {
      this.utilityService.openGoogleMap(this.userProfileData.native_latitude, this.userProfileData.native_longitude);
    } else if (type === 'current') {
      this.utilityService.openGoogleMap(this.userProfileData.latitude, this.userProfileData.longitude);
    }
  }
}
