import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DomainOmsService } from '@domain/oms';
import { PickupShelfIOService } from '@domain/pickup-shelf';
import { SharedHistoryListModule } from '@shared/components/history';
import { IconModule } from '@shared/components/icon';
import { PickUpShelfOutNavigationService, PickupShelfInNavigationService } from '@shared/services/navigation';
import { DBHOrderItemListItemDTO } from '@generated/swagger/oms-api';
import { Observable, combineLatest } from 'rxjs';
import { map, shareReplay, switchMap, take } from 'rxjs/operators';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { PickupShelfDetailsBaseComponent } from '../../pickup-shelf-details-base.component';

@Component({
  selector: 'page-pickup-shelf-history',
  templateUrl: 'pickup-shelf-history.component.html',
  styleUrls: ['pickup-shelf-history.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'page-pickup-shelf-history' },
  imports: [AsyncPipe, SharedHistoryListModule, IconModule],
})
export class PickUpShelfHistoryComponent extends PickupShelfDetailsBaseComponent {
  compartmentCode$: Observable<string> = this._activatedRoute.params.pipe(
    map((params) => decodeURIComponent(params?.compartmentCode ?? '') || undefined),
  );

  orderNumber$: Observable<string> = this._activatedRoute.params.pipe(
    map((params) => decodeURIComponent(params?.orderNumber ?? '') || undefined),
  );

  get orderItemSubsetId() {
    return +this._activatedRoute.snapshot.queryParams.orderItemSubsetId;
  }

  historyItem$ = combineLatest([this.orderNumber$, this.compartmentCode$]).pipe(
    switchMap(([orderNumber, compartmentCode]) =>
      this._pickupShelfIOService
        .getOrderItemsByOrderNumberOrCompartmentCode({ compartmentCode, orderNumber })
        .pipe(
          map((response) =>
            response?.result?.find((listItem) => listItem?.orderItemSubsetId === this.orderItemSubsetId),
          ),
        ),
    ),
    shareReplay(),
  );

  customerName$ = this.historyItem$.pipe(
    map((historyItem) =>
      [historyItem?.organisation ?? historyItem?.organisation, historyItem?.lastName, historyItem?.firstName]
        .filter((i) => !!i)
        .join(', '),
    ),
  );

  customerNumber$ = this.historyItem$.pipe(map((historyItem) => historyItem?.buyerNumber));

  history$ = this.historyItem$.pipe(
    switchMap((historyItem) => this._omsService.getHistory(historyItem?.orderItemSubsetId).pipe(take(1))),
  );

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _router: Router,
    private _shelfOutNavigation: PickUpShelfOutNavigationService,
    private _shelfInNavigation: PickupShelfInNavigationService,
    private _omsService: DomainOmsService,
    private _pickupShelfIOService: PickupShelfIOService,
  ) {
    super();
  }

  async navigateToShelfOutDetailsPage(item: DBHOrderItemListItemDTO) {
    await this._router.navigate(
      this._shelfOutNavigation.detailRoute({
        processId: this.listStore.processId,
        item: {
          compartmentCode: item.compartmentCode,
          orderId: item.orderId,
          orderNumber: item.orderNumber,
          processingStatus: item.processingStatus,
          compartmentInfo: item.compartmentInfo,
        },
      }).path,
      { queryParamsHandling: 'preserve' },
    );
  }

  async navigateToShelfInDetailsPage(item: DBHOrderItemListItemDTO) {
    await this._router.navigate(
      this._shelfInNavigation.detailRoute({
        item: {
          compartmentCode: item.compartmentCode,
          orderId: item.orderId,
          orderNumber: item.orderNumber,
          processingStatus: item.processingStatus,
          orderItemSubsetId: item.orderItemSubsetId,
          compartmentInfo: item.compartmentInfo,
        },
        side: coerceBooleanProperty(this._activatedRoute?.snapshot?.queryParams?.side),
      }).path,
      { queryParamsHandling: 'preserve' },
    );
  }
}
