import { ChangeDetectionStrategy, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { UiFilter } from '@ui/filter';
import { isEqual } from 'lodash';
import { BehaviorSubject, Subject } from 'rxjs';
import { first, takeUntil } from 'rxjs/operators';
import { TaskCalendarStore } from '../../task-calendar.store';

@Component({
  selector: 'page-task-calendar-filter',
  templateUrl: 'task-calendar-filter.component.html',
  styleUrls: ['task-calendar-filter.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class TaskCalendarFilterComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject<void>();
  @Output() exitFilter = new EventEmitter<void>();

  filter$ = new BehaviorSubject<UiFilter>(undefined);

  fetching$ = this.taskCalendarStore.selectFetchingFilter;

  message$ = this.taskCalendarStore.selectMessage;

  constructor(
    private taskCalendarStore: TaskCalendarStore,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _breadcrumb: BreadcrumbService,
    private _config: Config,
  ) {}

  private _initFilter(filter: UiFilter) {
    this.filter$.next(UiFilter.create(filter));
  }

  async ngOnInit() {
    this.taskCalendarStore.selectFilter.pipe(takeUntil(this._onDestroy$)).subscribe((filter) => {
      this._initFilter(filter);
    });

    const filter = await this.taskCalendarStore.selectFilter.pipe(first()).toPromise();
    this._initFilter(filter);
  }

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

  updateBreadcrumbs(params?: Params) {
    this._breadcrumb.patchBreadcrumbByKeyAndTags(this._config.get('process.ids.taskCalendar'), ['task-calendar'], {
      params,
    });
  }

  async applyFilter(filters: UiFilter) {
    const queryParams = { ...filters?.getQueryParams() };

    this.taskCalendarStore.setFilter({ filters });
    this.taskCalendarStore.setMessage({ message: '' });

    const search = this.getSearch(filters);
    if (search?.length >= 3 || search === '') {
      this.updateBreadcrumbs(queryParams);
      this.navigate('/filiale/task-calendar/search', queryParams);

      // ActivatedRouteChange wird nicht aufgerufen, wenn sich die URL nicht verändert. In dem Fall erneute Suche ausführen
      const isSearchPage = this._router.url.startsWith('/filiale/task-calendar/search?');
      if (isSearchPage && isEqual(filters.getQueryParams(), this._activatedRoute.snapshot.queryParams)) {
        this.taskCalendarStore.search({ clear: true });
      }

      this.exitFilter.emit();
    } else {
      this.taskCalendarStore.setMessage({ message: 'Mindestens 3 Zeichen' });
    }
  }

  getSearch(filter: UiFilter) {
    return filter?.input?.find((_) => true)?.input?.find((_) => true)?.value || '';
  }

  resetFilter() {
    this.taskCalendarStore.loadFilter();
  }

  navigate(uri: string, queryParams?: Params) {
    this._router.navigate([uri], { queryParams });
  }
}
