import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, signal } from '@angular/core';
import { EngagementListResult, Question, SubmitQuestionInput } from '../../../../../../core/products/models/product-engagement.model';
import { TranslatePipe } from '../../../../../../i18n/translate.pipe';
import { QuestionCardComponent } from '../question-card/question-card.component';
import { QuestionFormComponent } from '../question-form/question-form.component';
import { EmptyStateComponent } from '../../../../../../shared/ui/empty-state/empty-state.component';

@Component({
  selector: 'app-question-list',
  standalone: true,
  imports: [QuestionCardComponent, QuestionFormComponent, TranslatePipe, EmptyStateComponent],
  templateUrl: './question-list.component.html',
  styleUrls: ['./question-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class QuestionListComponent {
  @Input() result: EngagementListResult<Question> | null = null;
  @Input() loading = false;
  @Input() submitting = false;
  @Input() allowSubmission = true;

  @Output() pageChange = new EventEmitter<number>();
  @Output() submitQuestion = new EventEmitter<SubmitQuestionInput>();

  readonly askFormVisible = signal(false);

  get totalPages(): number {
    const total = this.result?.total ?? 0;
    const pageSize = this.result?.pageSize ?? 1;
    return Math.max(1, Math.ceil(total / pageSize));
  }

  previousPage(): void {
    if (!this.result || this.result.page <= 1) {
      return;
    }

    this.pageChange.emit(this.result.page - 1);
  }

  nextPage(): void {
    if (!this.result || this.result.page >= this.totalPages) {
      return;
    }

    this.pageChange.emit(this.result.page + 1);
  }

  onSubmit(payload: SubmitQuestionInput): void {
    this.submitQuestion.emit(payload);
    this.askFormVisible.set(false);
  }
}
