import { animate, style, transition, trigger } from '@angular/animations';
import { Component, ChangeDetectionStrategy, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { UiFilterAutocompleteProvider } from '@ui/filter';
import { isEqual } from 'lodash';
import { Subject } from 'rxjs';
import { filter, first, map, takeUntil, withLatestFrom } from 'rxjs/operators';

import { GoodsInSearchStore } from './goods-in-search.store';
import { GoodsInSearchMainAutocompleteProvider } from './providers/goods-in-search-main-autocomplete.provider';

@Component({
  selector: 'page-goods-in-search',
  templateUrl: 'goods-in-search.component.html',
  styleUrls: ['goods-in-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    GoodsInSearchStore,
    {
      provide: UiFilterAutocompleteProvider,
      useClass: GoodsInSearchMainAutocompleteProvider,
      multi: true,
    },
  ],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [style({ transform: 'translateX(100%)' }), animate('250ms', style({ transform: 'translateX(0%)' }))]),
      transition(':leave', [style({ transform: '*' }), animate('250ms', style({ transform: 'translateX(100%)' }))]),
    ]),
  ],
})
export class GoodsInSearchComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject();
  showFilterOverlay = false;

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

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

  constructor(
    private _goodsInSearchStore: GoodsInSearchStore,
    private _breadcrumb: BreadcrumbService,
    private _activatedRoute: ActivatedRoute,
    private readonly _config: Config
  ) {}

  ngOnInit() {
    this._goodsInSearchStore.loadSettings();
    this._activatedRoute.queryParams.pipe(takeUntil(this._onDestroy$)).subscribe((params) => {
      // Reset Filter when query params are empty
      if (params && Object.keys(params).length === 0) {
        this._goodsInSearchStore.setQueryParams(params);
        this._goodsInSearchStore.loadSettings();
      }
    });

    this._breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this._config.get('process.ids.goodsIn'),
      name: 'Abholfach',
      path: '/filiale/goods/in',
      tags: ['goods-in', 'main', 'filter'],
      section: 'branch',
    });
  }

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

  toggleFilterOverlay() {
    this.showFilterOverlay = !this.showFilterOverlay;
  }
}
