import { ChangeDetectionStrategy, Component, Input, OnInit, inject } from '@angular/core';
import { PickupShelfDetailsStore } from '../../store';
import { map } from 'rxjs/operators';
import { DBHOrderItemListItemDTO, OrderDTO } from '@generated/swagger/oms-api';
import { AsyncPipe } from '@angular/common';
import { IconModule } from '@shared/components/icon';

@Component({
  selector: 'page-pickup-shelf-details-items-group',
  templateUrl: 'pickup-shelf-details-items-group.component.html',
  styleUrls: ['pickup-shelf-details-items-group.component.scss'],
  host: { class: 'page-pickup-shelf-details-items-group' },
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [IconModule, AsyncPipe],
})
export class PickUpShelfDetailsItemsGroupComponent implements OnInit {
  private _store = inject(PickupShelfDetailsStore);

  get order(): OrderDTO {
    return this._store.order;
  }

  @Input() orderType: string;

  @Input() groupedItems: DBHOrderItemListItemDTO[];

  get firstGroupedItem() {
    return this.groupedItems?.find((_) => true);
  }

  openAddresses: boolean = false;

  get showAddresses(): boolean {
    return (
      (this.order?.orderType === 2 || this.order?.orderType === 4) && (!!this.order?.shipping || !!this.order?.billing)
    );
  }

  get showFeature(): boolean {
    return !!this.firstGroupedItem?.features && !!this.firstGroupedItem?.features?.orderType;
  }

  get targetBranches(): string {
    return Array.from(new Set(this.groupedItems?.map((item) => item?.targetBranch))).join('; ');
  }

  get isItemSelectable() {
    return this.groupedItems?.some((item) => !!item?.actions && item?.actions?.length > 0);
  }

  showMultiselect$ = this._store.fetchPartial$.pipe(
    map((fetchPartial) => this.isItemSelectable && fetchPartial && this.groupedItems?.length > 1),
  );

  selectedOrderItemCount$ = this._store.selectedOrderItemIds$.pipe(
    map(
      (ids) => this.groupedItems?.filter((groupedItem) => ids?.includes(groupedItem?.orderItemSubsetId))?.length ?? 0,
    ),
  );

  constructor() {}

  ngOnInit() {}

  selectAll() {
    this._store.selectAllOrderItemIds();
  }
}
