import { ChangeDetectionStrategy, Component, EventEmitter, inject, Input, Output } from '@angular/core';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { ProductCardComponent } from '../../../../../components/product-card/product-card.component';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { LanguageService } from '../../../../../services/language.service';
import { getTranslatedField, trackByItemId } from '../../../../../utils/item.utils';

export interface RelatedCollectionViewModel {
  id: string;
  title: string;
  products: Product[];
}

@Component({
  selector: 'app-related-products',
  standalone: true,
  imports: [ProductCardComponent, TranslatePipe],
  templateUrl: './related-products.component.html',
  styleUrls: ['./related-products.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RelatedProductsComponent {
  @Input() products: Product[] = [];
  @Input() collections: RelatedCollectionViewModel[] = [];

  @Output() productSelected = new EventEmitter<Product>();
  @Output() addToCart = new EventEmitter<{ product: Product; event: Event }>();

  private readonly languageService = inject(LanguageService);

  readonly trackByItemId = trackByItemId;

  get normalizedCollections(): RelatedCollectionViewModel[] {
    if (this.collections.length > 0) {
      return this.collections.filter(collection => collection.products.length > 0);
    }

    if (this.products.length === 0) {
      return [];
    }

    return [{
      id: 'default-related-products',
      title: 'itemDetail.relatedProducts',
      products: this.products,
    }];
  }

  productTitle(product: Product): string {
    return getTranslatedField(product, 'name', this.languageService.currentLanguage());
  }
}
