import { CommonModule } from '@angular/common';
import { Component, inject, Input, input, viewChild } from '@angular/core';
import { FormControl } from '@angular/forms';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable, Subject } from 'rxjs';

import { GetUserDetailsAction } from '../../../../../../shared/action/account.action';
import { FeedbackAction } from '../../../../../../shared/action/questions-answers.action';
import { QuestionModal } from '../../../../../../shared/components/widgets/modal/question-modal/question-modal';
import { NoData } from '../../../../../../shared/components/widgets/no-data/no-data';
import { IAccountUser } from '../../../../../../shared/interface/account.interface';
import { IProduct } from '../../../../../../shared/interface/product.interface';
import { IQuestionAnswers } from '../../../../../../shared/interface/questions-answers.interface';
import { QuestionsAnswersService } from '../../../../../../shared/services/questions-answers.service';
import { AccountState } from '../../../../../../shared/state/account.state';

@Component({
  selector: 'app-questions-answers',
  imports: [TranslateModule, CommonModule, NoData, QuestionModal],
  templateUrl: './questions-answers.html',
  styleUrl: './questions-answers.scss',
})
export class QuestionsAnswers {
  private store = inject(Store);
  public questionAnswersService = inject(QuestionsAnswersService);

  public user: IAccountUser;
  public question = new FormControl();
  public isLogin: boolean = false;
  public skeletonItems = Array.from({ length: 5 }, (_, index) => index);
  private destroy$ = new Subject<void>();

  readonly product = input<IProduct>();
  @Input() questionAnswers: IQuestionAnswers[];

  readonly QuestionModal = viewChild<QuestionModal>('questionModal');

  user$: Observable<IAccountUser> = inject(Store).select(
    AccountState.user,
  ) as Observable<IAccountUser>;

  constructor() {
    this.isLogin = !!this.store.selectSnapshot(state => state.auth && state.auth.access_token);
    if (this.isLogin) {
      this.store.dispatch(new GetUserDetailsAction());
    }
  }

  feedback(qna: IQuestionAnswers, value: string) {
    const data = {
      question_and_answer_id: qna.id,
      reaction: value,
    };
    this.store.dispatch(new FeedbackAction(data, value));
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
