import { CommonModule } from '@angular/common';
import { Component, ElementRef, inject, Input, SimpleChanges, viewChild } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { GetQuestionAnswersAction } from '../../../../../../shared/action/questions-answers.action';
import { GetReviewAction } from '../../../../../../shared/action/review.action';
import { IProduct } from '../../../../../../shared/interface/product.interface';
import { IQnAModel } from '../../../../../../shared/interface/questions-answers.interface';
import { IReviewModel } from '../../../../../../shared/interface/review.interface';
import { QuestionAnswersState } from '../../../../../../shared/state/questions-answers.state';
import { ReviewState } from '../../../../../../shared/state/review.state';
import { ProductReview } from '../product-review/product-review';
import { QuestionsAnswers } from '../questions-answers/questions-answers';

@Component({
  selector: 'app-product-details-tabs',
  imports: [TranslateModule, NgbModule, CommonModule, ProductReview, QuestionsAnswers],
  templateUrl: './product-details-tabs.html',
  styleUrl: './product-details-tabs.scss',
})
export class ProductDetailsTabs {
  private store = inject(Store);
  private sanitizer = inject(DomSanitizer);

  @Input() product: IProduct | null;

  question$: Observable<IQnAModel> = inject(Store).select(QuestionAnswersState.questionsAnswers);
  review$: Observable<IReviewModel> = inject(Store).select(ReviewState.review);

  public active = 'description';
  public showMore: boolean;
  public height: number;
  public width: number;

  readonly descriptionElement = viewChild<ElementRef>('description');

  ngAfterViewInit() {
    // Use a timeout to ensure that the element is rendered before trying to access its height
    setTimeout(() => {
      const description = this.descriptionElement()?.nativeElement;
      this.height = description?.offsetHeight;
      this.width = window.innerWidth;
    }, 0);
  }

  ngOnChanges(changes: SimpleChanges) {
    let product = changes['product']?.currentValue;
    this.store.dispatch(new GetQuestionAnswersAction({ product_id: product.id }));
    this.store.dispatch(new GetReviewAction({ product_id: product.id }));
  }

  getTrustedHtml(data?: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(data!);
  }

  seeMore() {
    this.showMore = !this.showMore;
  }
}
