import { IGoodResponse } from '@/domains/pos/models/good.io';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  EventEmitter,
  HostListener,
  inject,
  Output,
  signal,
} from '@angular/core';
import { ButtonDirective } from 'primeng/button';
import { Skeleton } from 'primeng/skeleton';
import images from 'src/assets/images';
import { PosLandingStore } from '../store/main.store';

@Component({
  selector: 'pos-goods-list-view',
  templateUrl: './list-view.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ButtonDirective, Skeleton],
})
export class PosGoodsListViewComponent {
  private readonly store = inject(PosLandingStore);
  @Output() onAdd = new EventEmitter<IGoodResponse>();

  goods = computed(() => this.store.filteredGoods());
  private readonly pageSize = 120;
  readonly renderLimit = signal(this.pageSize);
  visibleGoods = computed(() => this.goods()?.slice(0, this.renderLimit()));
  hasMore = computed(() => (this.goods()?.length || 0) > (this.visibleGoods()?.length || 0));
  loading = computed(() => this.store.getGoodsLoading());

  goodPlaceholder = images.placeholders.default;

  addGood(good: IGoodResponse) {
    this.onAdd.emit(good);
  }

  loadMore() {
    this.renderLimit.update((limit) => limit + this.pageSize);
  }

  @HostListener('window:scroll')
  onWindowScroll() {
    if (!this.hasMore()) return;
    const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 300;
    if (nearBottom) this.loadMore();
  }
}
