import { NgClass, NgFor, NgIf } from '@angular/common';
import { AfterViewInit, Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
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 { CommentList, PostList, UserData } from '@interfaces/common';
import { IonTextarea, IonicModule, NavController } from '@ionic/angular';
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-post-detail',
  templateUrl: './post-detail.page.html',
  styleUrls: ['./post-detail.page.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [IonicModule, NgClass, NgIf, PostComponent, NgFor, FormsModule]
})
export class PostDetailPage implements OnInit, AfterViewInit {
  @ViewChild('text') textElement: IonTextarea;
  postDetail: PostList;
  postId: string;
  commentValue: string;
  userData: UserData;
  pageNumber = 1;
  totalPage = 1;
  commentList: Array<CommentList> = [];
  totalCommentCount: number;
  type: string;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private stateManagementService: StateManagementService,
    private navCtrl: NavController,
    private utilityService: UtilityService
  ) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.postId = this.router.getCurrentNavigation().extras.state.postId;
      if (this.router.getCurrentNavigation().extras.state.type) {
        this.type = this.router.getCurrentNavigation().extras.state.type;
      }
    }
    if (this.route.snapshot.params.postId) {
      this.postId = this.route.snapshot.params.postId;
      this.type = this.route.snapshot.queryParams.type;
    }
  }

  get postType() {
    return (+this.type === 1) ? 'shravak' : (+this.type === 2) ? 'sant' : 'sangh';
  }

  ngOnInit() {
    this.getPostDetail();
  }

  async ionViewWillEnter() {
    this.userData = await this.stateManagementService.storage.get(GJainStorage.userData);
    if (this.type !== '3') {
      this.commentListing(false, '');
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      if (this.textElement) {
        this.textElement.autoGrow = true;
        this.textElement.setFocus();
      }
    }, 400);
  }

  getPostDetail() {
    this.httpRequestService.get(api.postDetail + '/' + this.postId).then((res: any) => {
      this.postDetail = res.data;
      this.type = res.data.type;
    });
  }

  addComment() {
    if (this.commentValue) {
      const params = {
        post_id: this.postId,
        comment: this.commentValue
      };
      this.httpRequestService.post(api.addComment, params).then((res: any) => {
        this.commentValue = '';
        if (this.commentList) {
          this.commentList.push(res.data.comment);
        } else {
          this.commentList = [res.data.comment];
        }
        if (this.postDetail) {
          this.postDetail.comments_count = res.data.comments_count;
        }
        this.totalCommentCount = res.data.comments_count;
        this.alert.showToaster(res.message);
      });
    }
  }

  moveToProfile(id) {
    if (id === this.userData.id) {
      this.navCtrl.navigateForward(Roots.page + '/' + Roots.shravakViewProfile);
    } else {
      this.navCtrl.navigateForward([Roots.page + '/' + Roots.shravakOtherProfile, { id }]);
    }
  }

  commentListing(isFirstLoad, event) {
    if (this.pageNumber <= this.totalPage) {
      const params = {
        page: this.pageNumber,
        limit: 10
      };
      this.httpRequestService.post(api.commentList.replace('{post_id}', String(this.postId)), params)
        .then((res: any) => {
          this.totalPage = res.data.last_page;
          this.totalCommentCount = res.data.total;
          if (this.postDetail) {
            this.postDetail.comments_count = this.totalCommentCount;
          }
          this.commentList.push(...res.data.data);
          if (isFirstLoad) { event.target.complete(); }
          this.pageNumber++;
        });
    }
  }

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

  trimString(stringValue, length) {
    return stringValue && stringValue.length > length ? stringValue.substring(0, length) + '...' : stringValue;
  }


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