import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
import { PickupShelfDetailsBaseComponent } from '../../pickup-shelf-details-base.component';
import { SharedGoodsInOutOrderEditModule } from '@shared/components/goods-in-out';
import { first } from 'rxjs/operators';
import { AsyncPipe } from '@angular/common';
import { PickupShelfInNavigationService } from '@shared/services/navigation';
import { DBHOrderItemListItemDTO } from '@generated/swagger/oms-api';

@Component({
  selector: 'page-pickup-shelf-in-edit',
  templateUrl: 'pickup-shelf-in-edit.component.html',
  styleUrls: ['pickup-shelf-in-edit.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'page-pickup-shelf-in-edit' },
  imports: [SharedGoodsInOutOrderEditModule, AsyncPipe],
})
export class PickupShelfInEditComponent extends PickupShelfDetailsBaseComponent {
  shelfInNavigation = inject(PickupShelfInNavigationService);

  constructor() {
    super();
  }

  async navigateToShelfInDetailsPage(changes?: Partial<DBHOrderItemListItemDTO>) {
    const orderId = (await this.store.orderItems$.pipe(first()).toPromise())?.find((_) => true)?.orderId;
    const orderNumber = decodeURIComponent(this.activatedRoute?.snapshot?.params?.orderNumber);
    let compartmentCode = changes?.compartmentCode ?? this.activatedRoute?.snapshot?.params?.compartmentCode;
    const processingStatus = changes?.processingStatus ?? this.activatedRoute.snapshot.params.orderItemProcessingStatus;
    let compartmentInfo = changes?.compartmentInfo ?? this.activatedRoute.snapshot.params.compartmentInfo;
    const item = this.store?.selectedOrderItem;

    if (compartmentCode) {
      compartmentCode = decodeURIComponent(compartmentCode);
    }

    if (compartmentInfo) {
      compartmentInfo = decodeURIComponent(compartmentInfo);
    }

    await this.router.navigate(
      this.shelfInNavigation.detailRoute({
        item: {
          orderId: orderId ? Number(orderId) : undefined,
          orderNumber,
          compartmentCode,
          processingStatus,
          compartmentInfo,
          orderItemSubsetId: item?.orderItemSubsetId,
        },
        side: this.side,
      }).path,
      { queryParamsHandling: 'preserve' },
    );
  }
}
