import { DatePipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { ApplicationService } from '@core/application';
import { EnvironmentService } from '@core/environment';
import { DomainAvailabilityService, DomainInStockService } from '@domain/availability';
import { ProductListItemDTO } from '@generated/swagger/wws-api';
import { DateAdapter } from '@ui/common';
import { debounceTime, filter, map, shareReplay, switchMap } from 'rxjs/operators';
import { PriceUpdateComponentStore } from '../price-update.component.store';
import { ReplaySubject, combineLatest } from 'rxjs';

@Component({
  selector: 'page-price-update-item',
  templateUrl: 'price-update-item.component.html',
  styleUrls: ['price-update-item.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [DatePipe],
  standalone: false,
})
export class PriceUpdateItemComponent {
  private _item$ = new ReplaySubject<ProductListItemDTO>(1);

  private _item: ProductListItemDTO;

  @Input()
  get item() {
    return this._item;
  }
  set item(value) {
    this._item = value;
    this._item$.next(value);
  }

  get publicationDate() {
    if (this.item?.product?.publicationDate) {
      const date = this._dateAdapter.parseDate(this.item.product.publicationDate);

      if (this._dateAdapter.getDate(date) === 1 && this._dateAdapter.getMonth(date) === 0) {
        return this._datePipe.transform(date, 'y');
      }

      return this._datePipe.transform(date, 'dd. MMMM y');
    }
    return '';
  }

  get isSelectable() {
    return this._store.isSelectable(this.item);
  }

  @Input() selected: boolean = false;

  defaultBranch$ = this._availability.getDefaultBranch();

  inStock$ = combineLatest([this.defaultBranch$, this._item$]).pipe(
    debounceTime(100),
    filter(([defaultBranch, item]) => !!defaultBranch && !!item),
    switchMap(([defaultBranch, item]) =>
      this._stockService.getInStock$({
        itemId: Number(item?.product?.catalogProductNumber),
        branchId: defaultBranch?.id,
      }),
    ),
  );

  constructor(
    private _dateAdapter: DateAdapter,
    private _datePipe: DatePipe,
    private _availability: DomainAvailabilityService,
    public applicationService: ApplicationService,
    public environment: EnvironmentService,
    private _stockService: DomainInStockService,
    private _store: PriceUpdateComponentStore,
  ) {}

  setSelected() {
    const isSelected = this._store.selectedItemUids.includes(this.item?.uId);
    this._store.setSelected({ selected: !isSelected, itemUid: this.item?.uId });
  }
}
