import { EventEmitter } from '@angular/core';
import { Component, ChangeDetectionStrategy, Input, Output } from '@angular/core';
import { ComponentStore } from '@ngrx/component-store';
import { StockInfoDTO } from '@swagger/remi';
import { OrderItemListItemDTO } from '@swagger/oms';
import { isEqual } from 'lodash';
import { map } from 'rxjs/operators';

export interface GoodsInOutOrderGroupItemState {
  item?: OrderItemListItemDTO;
  selected: boolean;
  selectable: boolean;
  quantityEditable: boolean;
}

@Component({
  selector: 'shared-goods-in-out-order-group-item',
  templateUrl: 'goods-in-out-order-group-item.component.html',
  styleUrls: ['goods-in-out-order-group-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GoodsInOutOrderGroupItemComponent extends ComponentStore<GoodsInOutOrderGroupItemState> {
  state$ = this.select((s) => s);

  @Input()
  get item() {
    return this.get((s) => s.item);
  }
  set item(item: OrderItemListItemDTO) {
    if (!isEqual(this.item, item)) {
      this.patchState({ item });
    }
  }

  readonly item$ = this.select((s) => s.item);

  @Input()
  get selected() {
    return this.get((s) => s.selected);
  }
  set selected(selected: boolean) {
    if (this.selected !== selected) {
      this.patchState({ selected });
    }
  }
  readonly selected$ = this.select((s) => s.selected);

  @Output()
  selectedChange = new EventEmitter<boolean>();

  @Input()
  get selectable() {
    return this.get((s) => s.selectable);
  }
  set selectable(selectable: boolean) {
    if (this.selectable !== selectable) {
      this.patchState({ selectable });
    }
  }

  @Input()
  get quantityEditable() {
    return this.get((s) => s.quantityEditable);
  }
  set quantityEditable(quantityEditable: boolean) {
    if (this.quantityEditable !== quantityEditable) {
      this.patchState({ quantityEditable });
    }
  }
  readonly quantityEditable$ = this.select((s) => s.quantityEditable);

  showChangeDate$ = this.item$.pipe(map((item) => [256, 512, 1024, 2048, 4069].includes(item?.processingStatus)));

  @Input()
  showCompartmentCode: boolean;

  @Input()
  showSupplier: boolean;

  @Input()
  showInStock: StockInfoDTO[];

  constructor() {
    super({
      selected: false,
      selectable: false,
      quantityEditable: false,
    });
  }

  getInStock(ean: string): number {
    if (!ean) {
      return 0;
    }

    const stockInfo = this.showInStock?.find((stock) => stock?.ean === ean);
    if (stockInfo) {
      return stockInfo?.inStock - (stockInfo?.removedFromStock || 0);
    } else {
      return 0;
    }
  }

  setSelected(selected: boolean) {
    this.selected = selected;
    this.selectedChange.emit(selected);
  }
}
