import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { ChangeDetectionStrategy, Component, Input, OnChanges, ViewChild } from '@angular/core';
import { ProductListItemDTO } from '@generated/swagger/wws-api';
import { map } from 'rxjs/operators';
import { PriceUpdateComponentStore } from '../price-update.component.store';
import { trigger, transition, style, animate } from '@angular/animations';

@Component({
  selector: 'page-price-update-list',
  templateUrl: 'price-update-list.component.html',
  styleUrls: ['price-update-list.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('cta', [
      transition(':enter', [
        style({ transform: 'scale(1.2)', opacity: 0 }),
        animate('250ms cubic-bezier(0.35, 0, 0.25, 1)', style({ transform: 'scale(1)', opacity: 1 })),
      ]),
      transition(':leave', [
        animate('250ms cubic-bezier(0.35, 0, 0.25, 1)', style({ transform: 'scale(0.8)', opacity: 0 })),
      ]),
    ]),
  ],
  standalone: false,
})
export class PriceUpdateListComponent {
  @ViewChild('scrollContainer', { static: true })
  scrollContainer: CdkVirtualScrollViewport;

  @Input()
  items: ProductListItemDTO[] = [];

  @Input()
  fetching: boolean = false;

  selectedItemUids$ = this._store.selectedItemUids$;

  loading$ = this._store.loading$;

  orderBy$ = this._store.filter$.pipe(map((filter) => filter?.orderBy));

  trackByFn = (index: number, item: ProductListItemDTO) => item.uId;

  constructor(private _store: PriceUpdateComponentStore) {}

  getSelectableItems() {
    return this._store.items.filter((item) => this._store.isSelectable(item)) ?? [];
  }

  isSelected(item: ProductListItemDTO) {
    return this._store.selectedItemUids.includes(item.uId);
  }

  selectAll() {
    const selectedItemUids = this.getSelectableItems().map((item) => item.uId);
    this._store.patchState({ selectedItemUids });
  }

  unselectAll() {
    this._store.patchState({ selectedItemUids: [] });
  }

  print() {
    this._store.print();
  }

  onComplete() {
    this._store.complete();
  }

  search() {
    this._store.fetchItems();
  }
}
