import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { CatalogLayoutMode } from '../../../../../core/products/models/catalog-experience.model';
import { CatalogProductGridComponent } from '../product-grid/product-grid.component';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { EmptyStateComponent } from '../../../../../shared/ui/empty-state/empty-state.component';
import { IconComponent } from '../../../../../shared/ui/icon/icon.component';
import { SkeletonComponent } from '../../../../../shared/ui/skeleton/skeleton.component';

@Component({
  selector: 'app-catalog-search-results',
  standalone: true,
  imports: [CatalogProductGridComponent, TranslatePipe, EmptyStateComponent, IconComponent, SkeletonComponent],
  templateUrl: './search-results.component.html',
  styleUrls: ['./search-results.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CatalogSearchResultsComponent {
  @Input() products: Product[] = [];
  @Input() total = 0;
  @Input() page = 1;
  @Input() pageSize = 24;
  @Input() summary = '';
  @Input() loading = false;
  @Input() layout: CatalogLayoutMode = 'grid';
  @Input() showRatings = true;
  @Input() showDiscounts = true;
  @Input() showAvailability = true;
  @Input() showShareAction = true;
  @Input() favoriteIds: number[] = [];
  @Input() comparedIds: number[] = [];
  @Input() loadingStrategy: 'pagination' | 'loadMore' | 'infiniteScroll' = 'pagination';
  @Input() hasMore = false;
  @Input() searchQuery = '';
  @Input() queryTooShort = false;
  @Input() minSearchLength = 3;

  @Output() pageChange = new EventEmitter<number>();
  @Output() loadMore = new EventEmitter<void>();
  @Output() productSelected = new EventEmitter<Product>();
  @Output() addToCart = new EventEmitter<{ product: Product; event: Event }>();
  @Output() productPreview = new EventEmitter<number>();
  @Output() quickView = new EventEmitter<number>();
  @Output() favoriteToggled = new EventEmitter<Product>();
  @Output() compareToggled = new EventEmitter<Product>();
  @Output() shareRequested = new EventEmitter<Product>();

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

  previous(): void {
    if (this.page > 1) {
      this.pageChange.emit(this.page - 1);
    }
  }

  next(): void {
    if (this.page < this.totalPages) {
      this.pageChange.emit(this.page + 1);
    }
  }

  onLoadMore(): void {
    if (this.hasMore) {
      this.loadMore.emit();
    }
  }
}
