import { NgClass, NgFor, NgIf } from '@angular/common';
import { AfterViewInit, CUSTOM_ELEMENTS_SCHEMA, Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { Share, ShareOptions } from '@capacitor/share';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { environment } from '@environments/environment';
import { PostList } from '@interfaces/common';
import { IonPopover, IonicModule, ModalController, NavController } from '@ionic/angular';
import { TaggedUserPage } from '@pages/post/tagged-user/tagged-user.page';
import { ClickableLinkPipe } from '@pipes/clickable-link.pipe';
import { HighlightMentionsPipe } from '@pipes/highlight-mentions.pipe';
import { SafeHtmlPipe } from '@pipes/safe-html.pipe';
import { HttpRequestService } from '@services/http-request.service';
import { UtilityService } from '@services/utility.service';
import { register } from 'swiper/element/bundle';

register();

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.scss'],
  standalone: true,
  imports: [IonicModule, NgIf, NgFor, NgClass, SafeHtmlPipe, ClickableLinkPipe, HighlightMentionsPipe],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class PostComponent implements AfterViewInit {
  @Output() updatePostEvent = new EventEmitter<PostList>();
  @Output() deletePostEvent = new EventEmitter<string>();
  @ViewChild('description') description: ElementRef;
  @ViewChild('postOption') postOption: IonPopover;
  postData: PostList;
  postType: 'sant' | 'sangh' | 'shravak';
  userId: number;
  isEditable = Boolean(false);
  diffPage: string;
  showMore = false;
  hasMoreDesc = false;
  isOpenOptions = false;
  toggleLike = false;

  constructor(
    private navCtrl: NavController,
    private modalController: ModalController,
    private httpRequestService: HttpRequestService,
    private utilityService: UtilityService
  ) { }

  get defaultImg() {
    return `/assets/images/${this.postType === 'shravak' ? 'shravak-profile.png' :
      this.postType === 'sangh' ? 'sangh-profile.png' : 'sant-profile.png'}`;
  }

  @Input() set _postData(value: PostList) {
    this.postData = value;
  }

  @Input() set _type(value: 'sant' | 'sangh' | 'shravak') {
    this.postType = value;
  }

  @Input() set _currentUserId(value: number) {
    this.userId = value;
  }

  @Input() set _isEditable(value: boolean) {
    this.isEditable = value;
  }

  @Input() set _fromPage(value: string) {
    this.diffPage = value || 'default';
  }

  ngAfterViewInit(): void {
    const el = this.description.nativeElement;
    setTimeout(() => {
      this.hasMoreDesc = el.offsetHeight < el.scrollHeight || el.offsetWidth < el.scrollWidth;
    }, 300);
  }

  async onModelOpen(taggedUsers) {
    const componentProps = {
      taggedUsers
    };
    const modal = await this.modalController.create({
      component: TaggedUserPage,
      componentProps,
      mode: 'ios',
      backdropDismiss: true,
      breakpoints: [0.1, 0.2, 1],
      initialBreakpoint: 0.2,
    });
    return await modal.present();
  }

  openReport(id) {
    this.utilityService.openReport({ postId: id, type: this.postType });
  }

  hidePost(post) {
    this.utilityService.hidePost(post);
  }

  postDetail(post: PostList) {
    const navOption = {
      state: {
        postId: post.id,
        type: this.postType === 'shravak' ? '1' : '3'
      },
    };
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.postDetail, navOption);
  }

  likeDislikePost(post, id) {
    const params = {
      post_id: id,
    };
    this.httpRequestService.post(api.likeDislikePost, params).then((res: any) => {
      post.is_liked = !post.is_liked;
      post.likes_count = res.data.likes_count;
      this.toggleLike = post.is_liked;
    });
  }

  async updatePost(postInfo) {
    this.updatePostEvent.emit(postInfo);
  }

  async deletePost(postId) {
    this.deletePostEvent.emit(postId);
  }

  async sharePost() {
    const url = `${environment.siteUrl}/page/post-detail/${this.postData.id}?type=${this.postType === 'shravak' ? '1' : '3'}`;
    const options: ShareOptions = { url };
    await Share.share(options);
  }

  moveToProfile() {
    if (this.postType === 'shravak') {
      this.moveToShravak(this.postData.user_id);
    } else if (this.postType === 'sangh') {
      this.moveToSangh(this.postData.sangh_details.id);
    } else {
      this.moveToSant(this.postData.subject.id);
    }
  }

  moveToShravak(shravakId) {
    if (shravakId === this.userId) {
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.shravakViewProfile);
    } else {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile.replace(':id', shravakId)]);
    }
  }

  moveToSangh(sanghId) {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.sanghProfile.replace(':sanghId', sanghId));
  }

  moveToSant(santId) {
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.santViewProfile.replace(':santId', santId));
  }

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

  imagePreview(imgName: string) {
    this.utilityService.imagePreview(imgName);
  }

  openOptions(e: Event) {
    this.postOption.event = e;
    this.isOpenOptions = true;
  }

}
