import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { EnvironmentService } from '@core/environment';
import { DomainCustomerOrderService, DomainGoodsService, DomainOmsService } from '@domain/oms';
import { CustomerOrdersNavigationService } from '@shared/services/navigation';
import { DBHOrderItemListItemDTO, OrderItemListItemDTO } from '@generated/swagger/oms-api';
import { UiMessageModalComponent, UiModalService } from '@ui/modal';
import { combineLatest, Observable } from 'rxjs';
import { map, shareReplay, switchMap, tap, withLatestFrom } from 'rxjs/operators';

@Component({
  selector: 'page-customer-order-edit',
  templateUrl: 'customer-order-edit.component.html',
  styleUrls: ['customer-order-edit.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class CustomerOrderEditComponent 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)),
  );

  processingStatus$ = this._activatedRoute.params.pipe(map((params) => params?.processingStatus || undefined));

  archive$ = this._activatedRoute.queryParams.pipe(map((params) => params?.archive || false));

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

  buyerNumber$ = this._activatedRoute.queryParams.pipe(map((params) => params.buyerNumber));

  items$ = combineLatest([this.orderId$, this.compartmentCode$]).pipe(
    switchMap(([orderId, compartmentCode]) => {
      return this._domainCustomerOrderService.getOrderItemsByOrderNumber({
        compartmentCode,
        orderId,
      });
    }),
    withLatestFrom(this.processingStatus$, this.buyerNumber$),
    map(([response, processingStatus, buyerNumber]) => {
      return response?.result?.filter(
        (item) =>
          item.processingStatus === +processingStatus && (buyerNumber ? item.buyerNumber === buyerNumber : true),
      );
    }),
    tap((items) => this.openModalIfItemsHaveDifferentCustomers(items)),
    shareReplay(),
  );

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

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _breadcrumb: BreadcrumbService,
    private _domainCustomerOrderService: DomainCustomerOrderService,
    private _navigation: CustomerOrdersNavigationService,
    private _uiModal: UiModalService,
    private _environment: EnvironmentService,
  ) {}

  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: 'Bearbeiten',
      path: this._navigation.getCustomerOrdersEditPath({
        processId: this.processId,
        processingStatus,
        compartmentCode: compartmentCode ?? undefined,
        orderId: Number(orderId),
      }).path,
      section: 'customer',
      params: this._activatedRoute.snapshot.queryParams,
      tags: ['customer-order', 'edit', compartmentCode || orderId],
    });
  }

  async navigateToDetailsPage(changes?: Partial<DBHOrderItemListItemDTO>) {
    const orderId = this._activatedRoute.snapshot.params.orderId;
    const compartmentCode = this._activatedRoute.snapshot.params.compartmentCode;
    const processingStatus = changes?.processingStatus
      ? changes.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();
  }

  openModalIfItemsHaveDifferentCustomers(items: OrderItemListItemDTO[]) {
    const buyerNumbers = new Set(items.map((item) => item.buyerNumber));
    if (buyerNumbers.size > 1) {
      this._uiModal.open({
        content: UiMessageModalComponent,
        title: 'Achtung',
        data: {
          message:
            'Anzeige ist fehlerhaft.\nEs wurden mehrere Positionen gefunden, die unterschiedlichen Kunden zugeordnet sind.',
        },
      });
    }
  }
}
