import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { IonicModule, NavController, PopoverController } from '@ionic/angular';

import { NgClass, NgFor, NgIf } from '@angular/common';
import { SocialSharing } from '@awesome-cordova-plugins/social-sharing/ngx';
import { FooterComponent } from '@components/footer/footer.component';
import { JoinSanghButtonComponent } from '@components/join-sangh-button/join-sangh-button.component';
import { PostComponent } from '@components/post/post.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 { SanghProfileData, UserData } from '@interfaces/common';
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-profile',
  templateUrl: './sangh-profile.page.html',
  styleUrls: ['./sangh-profile.page.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgClass, JoinSanghButtonComponent, NgFor, PostComponent, FooterComponent],
  providers: [SocialSharing]
})
export class SanghProfilePage implements OnInit {
  sanghData: SanghProfileData;
  sanghId: string;
  postList = [];
  pageNumber = 1;
  totalPage = 1;
  userData: UserData;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private activatedRoute: ActivatedRoute,
    private navCtrl: NavController,
    private popoverCtrl: PopoverController,
    private stateManagementService: StateManagementService,
    public utilityService: UtilityService,
    private socialSharing: SocialSharing
  ) { }

  ngOnInit() {
    this.sanghId = this.activatedRoute.snapshot.paramMap.get('sanghId');
  }

  async ionViewWillEnter() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
    this.getProfileInfo();
    this.postList = [];
    this.pageNumber = 1;
    this.totalPage = 1;
    this.getPostList(false, '');
  }

  getProfileInfo() {
    this.httpRequestService.get(api.sanghProfile.replace('{id}', this.activatedRoute.snapshot.paramMap.get('sanghId'))).then((res: any) => {
      this.sanghData = res.data;
    });
  }

  getPostList(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const params = {
        page: this.pageNumber,
        limit: 5,
        sangh_id: Number(this.sanghId)
      };
      this.httpRequestService.post(api.sanghPostList, params).then((res: any) => {
        this.totalPage = res.data.last_page;
        this.pageNumber = res.data.current_page + 1;
        for (const d of res.data.data) {
          const index = this.postList.findIndex(object => object.id === d.id);
          if (index === -1) {
            this.postList.push(d);
          }
        }
        if (isFirstLoad) {
          event.target.complete();
        }
        this.pageNumber++;
      });
    } else {
      event.target.complete();
    }
  }

  updatePost(postInfo) {
    this.popoverCtrl.dismiss().then(() => {
      const navOption = {
        state: {
          postData: postInfo,
          isUpdate: true,
          fromFeed: true,
          redirectTo: `page/sangh-profile/${this.sanghId}`,
          type: 3,
          type_id: Number(this.sanghId),
          userAvatar: this.sanghData?.avatar,
          userName: this.sanghData?.name
        },
      };
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
    });
  }

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

  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);
      });
    }
  }

  async followSangh(event, sanghData: any) {
    // --- follow sangh
    const followSangh = async () => {
      await this.httpRequestService.post(api.followSangh, {
        sangh_id: this.sanghData.id,
      });
      this.sanghData.is_user_following = !this.sanghData.is_user_following;
    };

    event.stopPropagation();
    if (sanghData.is_user_following) {
      const isYes = await this.utilityService.presentConfirm(
        'Are you sure you want to unfollow?',
        'No', 'Yes', 'Unfollow'
      );
      if (isYes) {
        await followSangh();
      }
    } else {
      await followSangh();
    }
  }

  createPost() {
    const navOption = {
      state: {
        isUpdate: false,
        fromFeed: true,
        redirectTo: `page/sangh-profile/${this.sanghId}`,
        type: 3,
        type_id: Number(this.sanghId),
        userAvatar: this.sanghData?.avatar,
        userName: this.sanghData?.name
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed, navOption);
  }

  editProfile() {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.sanghEditProfile, { id: this.sanghData.id }]);
  }

  memberCard() {
    this.navCtrl.navigateForward([Roots.page + '/' + Roots.sanghMemberCard, { id: this.sanghData.id }]);
  }

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

  membersDetail() {
    this.navCtrl.navigateForward([
      Roots.page + '/' + Roots.sanghMembersAdminView,
      { id: this.sanghData.id, is_member: this.sanghData.is_member }
    ]);
  }

  viewVihar() {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.chaturmasVihar.replace(':sanghId', String(this.sanghData.id)));
  }

  aboutSangh() {
    const navOption = {
      state: {
        sanghData: this.sanghData,
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.aboutSangh, navOption);
  }

  async shareProfile() {

    const imageUrl = this.sanghData.avatar
    const redirectUrl = `${environment.siteUrl}/page/sangh-profile/${this.sanghId}`;

    try {
      await this.socialSharing.share(
        `*Our Shree Sangh is now on the Global Jain digital app!*\n\nWe encourage everyone to download the app, join the Sangh, and receive your member ID card.\n\n*हमारा श्री संघ अब ग्लोबल जैन डिजिटल ऐप पर है!*\n\nसभी से अनुरोध है कि ऐप डाउनलोड करें, संघ के सदस्य बनें, और अपना सदस्यता आईडी कार्ड प्राप्त करें।\n\n*Membership link:* ${redirectUrl}\n\nAlternatively, you can fill details in the below link and submit:https://form.jotform.com/242238674400049`,
        'Invite Member',
        imageUrl
      );
    } catch (error) {
      console.error('Error sharing content:', error);
    }
  }

  addressPost(element) {
    this.utilityService.openGoogleMap(element.latitude, element.longitude);
  }

}
