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 { UiFilter, UiFilterAutocompleteProvider } from '@ui/filter';
import { isEqual } from 'lodash';
import { combineLatest, Subject } from 'rxjs';
import { map, takeUntil, withLatestFrom } from 'rxjs/operators';
import { GoodsOutSearchStore } from './goods-out-search.store';
import { GoodsOutSearchMainAutocompleteProvider } from './providers/goods-out-search-main-autocomplete.provider';

@Component({
  selector: 'page-goods-out-search',
  templateUrl: 'goods-out-search.component.html',
  styleUrls: ['goods-out-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    GoodsOutSearchStore,
    {
      provide: UiFilterAutocompleteProvider,
      useClass: GoodsOutSearchMainAutocompleteProvider,
      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 GoodsOutSearchComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject();
  showFilterOverlay = false;

  hasFilter$ = combineLatest([this._goodsOutSearchStore.filter$, this._goodsOutSearchStore.defaultSettings$]).pipe(
    map(([filter, defaultFilter]) => !isEqual(filter?.getQueryParams(), UiFilter.create(defaultFilter).getQueryParams()))
  );

  processId$ = this._activatedRoute.data.pipe(map((data) => +data.processId));

  constructor(
    private _goodsOutSearchStore: GoodsOutSearchStore,
    private _breadcrumb: BreadcrumbService,
    private _activatedRoute: ActivatedRoute
  ) {}

  ngOnInit() {
    this._goodsOutSearchStore.loadSettings();

    this.processId$.pipe(takeUntil(this._onDestroy$), withLatestFrom(this._activatedRoute.queryParams)).subscribe(([processId]) => {
      // if (params && Object.keys(params).length === 0) {
      //   console.log('params is empty');
      //   this._goodsOutSearchStore.setQueryParams(params);
      //   this._goodsOutSearchStore.loadSettings();
      // } else {
      //   // this._goodsOutSearchStore.resetFilter(params);
      // }

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

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

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