import { Component, ChangeDetectionStrategy, Output, EventEmitter, ChangeDetectorRef, OnInit, OnDestroy, Input } from '@angular/core';
import { Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { OrderItemListItemDTO } from '@swagger/oms';
import { UiFilter } from '@ui/filter';
import { Observable, Subject } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { GoodsOutSearchStore } from '../goods-out-search.store';

@Component({
  selector: 'page-goods-out-search-filter',
  templateUrl: 'goods-out-search-filter.component.html',
  styleUrls: ['goods-out-search-filter.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GoodsOutSearchFilterComponent implements OnInit, OnDestroy {
  @Output()
  close = new EventEmitter();

  filter: UiFilter;

  loading$: Observable<boolean>;

  message: string;

  @Input()
  processId: number;

  private _onDestroy$ = new Subject();

  constructor(
    private _goodsOutSearchStore: GoodsOutSearchStore,
    private _breadcrumb: BreadcrumbService,
    private _cdr: ChangeDetectorRef,
    private _router: Router,
    private readonly _config: Config
  ) {}

  ngOnInit() {
    this._initSettings();
    this._initLoading$();
  }

  ngOnDestroy() {
    this._onDestroy$.next();
    this._onDestroy$.complete();
  }

  private _initSettings() {
    this.filter = UiFilter.create(this._goodsOutSearchStore.filter);
  }

  private _initLoading$() {
    this.loading$ = this._goodsOutSearchStore.fetching$;
  }

  async resetFilter() {
    const queryParams = { main_qs: this.filter?.getQueryParams()?.main_qs || '' };
    this._goodsOutSearchStore.resetFilter(queryParams);
    this._initSettings();
    this._cdr.markForCheck();
  }

  async applyFilter() {
    this._goodsOutSearchStore.setFilter(this.filter);
    this.message = undefined;

    await this.updateQueryParams();

    this._goodsOutSearchStore.searchResult$.pipe(takeUntil(this._onDestroy$), take(1)).subscribe((result) => {
      if (result.error) {
      } else {
        if (result.hits > 0) {
          if (result.hits === 1) {
            const orderItem = result.result[0];
            this._router.navigate([this.getDetailsPath(orderItem)]);
          } else {
            this._router.navigate(['/kunde', this.processId, 'goods', 'out', 'results'], {
              queryParams: this._goodsOutSearchStore.filter.getQueryParams(),
            });
          }

          this.close.emit();
        } else {
          this.message = 'keine Suchergebnisse';
        }

        this._cdr.markForCheck();
      }
    });

    this._goodsOutSearchStore.search({ clear: true });
  }

  async updateBreadcrumb() {
    await this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this.processId,
      name: 'Warenausgabe',
      path: `/kunde/${this.processId}/goods/out`,
      tags: ['goods-out', 'main', 'filter'],
      section: 'customer',
      params: this._goodsOutSearchStore.filter?.getQueryParams(),
    });
  }

  async updateQueryParams() {
    await this._router.navigate([], { queryParams: this._goodsOutSearchStore.filter?.getQueryParams() });
    this.updateBreadcrumb();
  }

  getDetailsPath(item: OrderItemListItemDTO) {
    return item?.compartmentCode
      ? `/kunde/${this.processId}/goods/out/details/compartment/${encodeURIComponent(item?.compartmentCode)}/${item?.processingStatus}`
      : `/kunde/${this.processId}/goods/out/details/order/${encodeURIComponent(item?.orderNumber)}/${item?.processingStatus}`;
  }
}
