import { DatePipe } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Input,
  inject,
} from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import {
  NavigateOnClickDirective,
  ProductImageModule,
} from '@cdn/product-image';
import { EnvironmentService } from '@core/environment';
import { IconModule } from '@shared/components/icon';
import { DBHOrderItemListItemDTO } from '@generated/swagger/oms-api';
import { getOrderItemRewardFeature } from '@isa/oms/data-access';
import { LabelComponent } from '@isa/ui/label';
import { UiCommonModule } from '@ui/common';
import { PickupShelfProcessingStatusPipe } from '../pipes/processing-status.pipe';
import { FormsModule } from '@angular/forms';
import { PickupShelfStore } from '../../store';
import { map } from 'rxjs/operators';
import { CacheService } from '@core/cache';
import { MatomoModule } from 'ngx-matomo-client';

@Component({
  selector: 'page-pickup-shelf-list-item',
  templateUrl: 'pickup-shelf-list-item.component.html',
  styleUrls: ['pickup-shelf-list-item.component.css'],
  host: { class: 'page-pickup-shelf-list-item' },
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    FormsModule,
    RouterLink,
    RouterLinkActive,
    IconModule,
    DatePipe,
    ProductImageModule,
    UiCommonModule,
    PickupShelfProcessingStatusPipe,
    NavigateOnClickDirective,
    MatomoModule,
    LabelComponent,
  ],
  providers: [PickupShelfProcessingStatusPipe],
})
export class PickUpShelfListItemComponent {
  private cache = inject(CacheService);

  store = inject(PickupShelfStore);

  @Input() item: DBHOrderItemListItemDTO;

  @Input() primaryOutletActive = false;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  @Input() itemDetailsLink: any[] = [];

  @Input() isItemSelectable?: boolean = undefined;

  @Input() selectedItem?: DBHOrderItemListItemDTO;

  get isTablet() {
    return this._environment.matchTablet();
  }

  get isDesktopSmall() {
    return this._environment.matchDesktopSmall();
  }

  get isDesktopLarge() {
    return this._environment.matchDesktopLarge();
  }

  get contributors() {
    return this.item?.product?.contributors
      ?.split(';')
      .map((val) => val.trim());
  }

  get showChangeDate() {
    return [256, 512, 1024, 2048, 4069].includes(this.item?.processingStatus);
  }

  // Zeige nur CompartmentCode an wenn verfügbar
  get showCompartmentCode() {
    return (
      !!this.item?.compartmentCode &&
      (this.isTablet || this.isDesktopSmall || this.primaryOutletActive)
    );
  }

  get processingStatusColor() {
    return {
      'background-color': this._processingStatusPipe.transform(
        this.item?.processingStatus,
        true,
      ),
    };
  }

  /**
   * Indicates whether the order item has reward points (Lesepunkte).
   * Returns true if the item has a 'praemie' feature.
   */
  get hasRewardPoints() {
    return getOrderItemRewardFeature(this.item) !== undefined;
  }

  selected$ = this.store.selectedListItems$.pipe(
    map((selectedListItems) =>
      selectedListItems?.find(
        (item) => item?.orderItemSubsetId === this.item?.orderItemSubsetId,
      ),
    ),
  );

  constructor(
    private _elRef: ElementRef,
    private _environment: EnvironmentService,
    private _processingStatusPipe: PickupShelfProcessingStatusPipe,
  ) {}

  async onDetailsClick() {
    if (this.isDesktopLarge) {
      this.scrollIntoView();
    }

    if (!(await this.hasOrderItemInCache())) {
      this.addOrderItemIntoCache();
    }
  }

  async hasOrderItemInCache() {
    const items =
      (await this.cache.get<DBHOrderItemListItemDTO[]>({
        name: 'orderItems',
        orderId: this.item.orderId,
        compartmentCode: this.item.compartmentCode,
        compartmentInfo: this.item.compartmentInfo,
        orderItemProcessingStatus: this.item.processingStatus,
        store: 'PickupShelfDetailsStore',
      })) ?? [];

    return items.some(
      (i) => i.orderItemSubsetId === this.item.orderItemSubsetId,
    );
  }

  addOrderItemIntoCache() {
    this.cache.set(
      {
        name: 'orderItems',
        orderId: this.item.orderId,
        compartmentCode: this.item.compartmentCode,
        compartmentInfo: this.item.compartmentInfo,
        orderItemProcessingStatus: this.item.processingStatus,
        store: 'PickupShelfDetailsStore',
      },
      [this.item],
      { ttl: 10000 },
    );
  }

  scrollIntoView() {
    this._elRef.nativeElement.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
    });
  }

  setSelected() {
    const isSelected = this.store?.selectedListItems
      .map((items) => items?.orderItemSubsetId)
      .includes(this.item?.orderItemSubsetId);
    if (isSelected) {
      this.store.removeSelectedListItem(this.item);
    } else {
      this.store.addSelectedListItem(this.item);
    }
  }
}
