import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Observable, Subject } from 'rxjs';
import { map, takeUntil, withLatestFrom } from 'rxjs/operators';
import { ArticleSearchService } from './article-search.store';
import { FocusSearchboxEvent } from './focus-searchbox.event';
import { ArticleSearchMainAutocompleteProvider } from './providers';
import { ProductCatalogNavigationService } from '@shared/services/navigation';
import { FilterAutocompleteProvider } from '@shared/components/filter';

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

  constructor(
    private _breadcrumb: BreadcrumbService,
    private _articleSearch: ArticleSearchService,
    private _activatedRoute: ActivatedRoute,
    private _navigationService: ProductCatalogNavigationService,
  ) {}

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

  cleanupQueryParams(params: Record<string, string> = {}) {
    const clean = { ...params };

    for (const key in clean) {
      if (Object.prototype.hasOwnProperty.call(clean, key)) {
        if (clean[key] == undefined) {
          delete clean[key];
        }
      }
    }

    return clean;
  }

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

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

  resetFilter(queryParams: Record<string, string>) {
    if (Object.keys(queryParams).length === 0) {
      this._articleSearch.resetFilter();
    }
  }

  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: this._navigationService.getArticleSearchBasePath(processId).path,
      params: queryParams,
      tags: ['catalog', 'main'],
      section: 'customer',
    });
  }
}
