import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { DomainCustomerOrderService, DomainOmsService } from '@domain/oms';
import { CustomerOrdersNavigationService } from '@shared/services/navigation';
import { Observable, combineLatest } from 'rxjs';
import { map, switchMap, shareReplay, take } from 'rxjs/operators';

@Component({
  selector: 'page-customer-order-history',
  templateUrl: 'customer-order-history.component.html',
  styleUrls: ['customer-order-history.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class CustomerOrderHistoryComponent implements OnInit {
  get processId() {
    return +this._activatedRoute.snapshot.parent.data.processId;
  }

  processId$ = this._activatedRoute.parent.data.pipe(map((params) => +params.processId));

  orderId$: Observable<number> = this._activatedRoute.params.pipe(
    map((params) => (params.orderId ? Number(params.orderId) : undefined)),
  );

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

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

  historyItem$ = combineLatest([this.orderId$, this.compartmentCode$]).pipe(
    switchMap(([orderId, compartmentCode]) =>
      this._domainCustomerOrderService.getOrderItemsByOrderNumber({
        compartmentCode,
        orderId,
      }),
    ),
    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 _breadcrumb: BreadcrumbService,
    private _navigation: CustomerOrdersNavigationService,
    private _domainCustomerOrderService: DomainCustomerOrderService,
    private _omsService: DomainOmsService,
  ) {}

  ngOnInit() {
    this.updateBreadcrumb();
  }

  async updateBreadcrumb() {
    const orderId = this._activatedRoute.snapshot.params.orderId;
    const compartmentCode = this._activatedRoute.snapshot.params.compartmentCode;
    const processingStatus = this._activatedRoute.snapshot.params.processingStatus;
    await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this.processId,
      name: 'Historie',
      path: this._navigation.getCustomerOrdersHistoryPath({
        processId: this.processId,
        processingStatus,
        compartmentCode: compartmentCode ?? undefined,
        orderId: Number(orderId),
      }).path,
      section: 'customer',
      params: this._activatedRoute.snapshot.queryParams,
      tags: ['customer-order', 'history', compartmentCode || orderId],
    });
  }

  async navigateToDetailsPage({ options }: { options?: { processingStatus?: number } }) {
    const orderId = this._activatedRoute.snapshot.params.orderId;
    const compartmentCode = this._activatedRoute.snapshot.params.compartmentCode;
    const processingStatus = options?.processingStatus
      ? options.processingStatus
      : this._activatedRoute.snapshot.params.processingStatus;

    await this._navigation
      .getCustomerOrdersDetailsPath({
        processId: this.processId,
        processingStatus: processingStatus,
        compartmentCode: compartmentCode ?? undefined,
        orderId: orderId ? Number(orderId) : undefined,
        extras: { queryParams: this._activatedRoute.snapshot.queryParams },
      })
      .navigate();
  }
}
