import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { Component, ChangeDetectionStrategy, Input, ViewChild, OnChanges, SimpleChanges } from '@angular/core';
import { provideComponentStore } from '@ngrx/component-store';
import { PackageItemDTO } from '@generated/swagger/wws-api';
import { isEqual } from 'lodash';
import { asapScheduler } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
import { PackageDetailsListStore } from './package-details-list.store';

@Component({
  selector: 'page-package-details-list',
  templateUrl: 'package-details-list.component.html',
  styleUrls: ['package-details-list.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [provideComponentStore(PackageDetailsListStore)],
  standalone: false,
})
export class PackageDetailsListComponent implements OnChanges {
  @ViewChild(CdkVirtualScrollViewport, { static: true })
  viewport: CdkVirtualScrollViewport;

  @Input()
  hasActions = false;

  @Input()
  height: number;

  @Input()
  get items(): PackageItemDTO[] {
    return this._store.items;
  }
  set items(value: PackageItemDTO[]) {
    if (isEqual(this.items, value)) return;
  }

  @Input()
  get arrivalStatus() {
    return this._store.arrivalStatus;
  }
  set arrivalStatus(value) {
    if (isEqual(this.arrivalStatus, value)) return;
    this._store.setArrivalStatus(value ?? 0);
  }

  items$ = this._store.items$.pipe(distinctUntilChanged(isEqual));

  trackByItemId = (_: number, item: PackageItemDTO) => item?.id;

  constructor(private _store: PackageDetailsListStore) {}

  ngOnChanges({ height, arrivalStatus, items }: SimpleChanges) {
    if (height) {
      this.checkViewportSize();
    }

    if (arrivalStatus && items) {
      this._store.setItems(items.currentValue ?? [], arrivalStatus.currentValue !== 8);
    }
  }

  checkViewportSize() {
    asapScheduler.schedule(() => {
      this.viewport?.checkViewportSize();
    });
  }
}
