import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { EngagementListResult, Review, SubmitReviewInput } from '../../../../../../core/products/models/product-engagement.model';
import { RatingSummary } from '../../../../../../core/products/models/product-engagement.model';
import { TranslatePipe } from '../../../../../../i18n/translate.pipe';
import { RatingSummaryComponent } from '../rating-summary/rating-summary.component';
import { ReviewCardComponent } from '../review-card/review-card.component';
import { ReviewFormComponent } from '../review-form/review-form.component';
import { EmptyStateComponent } from '../../../../../../shared/ui/empty-state/empty-state.component';

@Component({
  selector: 'app-review-list',
  standalone: true,
  imports: [RatingSummaryComponent, ReviewCardComponent, ReviewFormComponent, TranslatePipe, EmptyStateComponent],
  templateUrl: './review-list.component.html',
  styleUrls: ['./review-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ReviewListComponent {
  @Input() result: EngagementListResult<Review> | null = null;
  @Input() ratingSummary: RatingSummary | null = null;
  @Input() loading = false;
  @Input() submitting = false;
  @Input() showSummary = true;
  @Input() mode: 'pages' | 'load-more' = 'pages';

  @Output() pageChange = new EventEmitter<number>();
  @Output() loadMore = new EventEmitter<number>();
  @Output() submitReview = new EventEmitter<SubmitReviewInput>();

  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);
  }

  onLoadMore(): void {
    if (!this.result || this.result.items.length >= this.result.total || this.loading) {
      return;
    }

    this.loadMore.emit((this.result.page ?? 1) + 1);
  }
}
