import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { UiFilterAutocompleteProvider } from '@ui/filter';
import { isEqual } from 'lodash';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { filter, first, map, takeUntil, withLatestFrom } from 'rxjs/operators';
import { ArticleSearchService } from './article-search.store';
import { FocusSearchboxEvent } from './focus-searchbox.event';
import { ArticleSearchMainAutocompleteProvider } from './providers';

@Component({
  selector: 'page-article-search',
  templateUrl: 'article-search.component.html',
  styleUrls: ['article-search.component.scss'],
  providers: [
    FocusSearchboxEvent,
    ArticleSearchService,
    {
      provide: UiFilterAutocompleteProvider,
      useClass: ArticleSearchMainAutocompleteProvider,
      multi: true,
    },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ArticleSearchComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject();
  private _processId$: Observable<number>;

  initialFilter$ = this._articleSearch.filter$.pipe(
    filter((filter) => !!filter),
    first()
  );

  hasFilter$ = this._articleSearch.filter$.pipe(
    withLatestFrom(this.initialFilter$),
    map(([filter, initialFilter]) => !isEqual(filter?.getQueryParams(), initialFilter?.getQueryParams()))
  );

  filterActive$ = new BehaviorSubject<boolean>(false);
  constructor(
    private _breadcrumb: BreadcrumbService,
    private _router: Router,
    private _articleSearch: ArticleSearchService,
    private _activatedRoute: ActivatedRoute
  ) {}

  ngOnInit() {
    this.initProcessId();
    this._activatedRoute.url
      .pipe(takeUntil(this._onDestroy$), withLatestFrom(this._activatedRoute.queryParams, this._processId$))
      .subscribe(([_, queryParams, processId]) => {
        this.removeBreadcrumbs(processId);
        this.addOrUpdateBreadcrumbs(processId, queryParams);
      });

    this._articleSearch.searchCompleted
      .pipe(takeUntil(this._onDestroy$), withLatestFrom(this._processId$))
      .subscribe(([state, processId]) => {
        if (state.searchState === '') {
          if (state.hits === 1) {
            const item = state.items.find((f) => f);
            this._router.navigate(['/kunde', processId, 'product', 'details', item.id]);
          } else {
            const params = state.filter.getQueryParams();
            this._router.navigate(['/kunde', processId, 'product', 'search', 'results'], {
              queryParams: params,
            });
          }
        }
      });
  }

  initProcessId() {
    this._processId$ = this._activatedRoute.parent.data.pipe(map((data) => Number(data.processId)));
  }

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

  async removeBreadcrumbs(processId: number) {
    this._breadcrumb.removeBreadcrumbsByKeyAndTags(processId, ['checkout']);
  }

  async addOrUpdateBreadcrumbs(processId: number, queryParams: Record<string, string>) {
    await this._breadcrumb.addBreadcrumbIfNotExists({
      key: processId,
      name: 'Artikelsuche',
      path: `/kunde/${processId}/product`,
      params: queryParams,
      tags: ['catalog', 'main'],
      section: 'customer',
    });
  }
}
