import { Component, ViewChild, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Config } from '@core/config';
import { UiFilter } from '@ui/filter';
import { delay, isEqual } from 'lodash';
import { BehaviorSubject, combineLatest, Subject } from 'rxjs';
import { first, map, shareReplay, takeUntil, debounceTime } from 'rxjs/operators';
import { TaskSearchbarComponent } from './components/task-searchbar/task-searchbar.component';
import { TaskCalendarStore } from './task-calendar.store';
import { ApplicationService } from '@core/application';

@Component({
  selector: 'page-task-calendar',
  templateUrl: 'page-task-calendar.component.html',
  styleUrls: ['page-task-calendar.component.scss'],
  providers: [TaskCalendarStore],
  standalone: false,
})
export class PageTaskCalendarComponent implements OnInit, OnDestroy {
  private _onDestroy$ = new Subject<void>();

  @ViewChild('searchInput', { static: true })
  searchInput: ElementRef;

  filterActive$ = new BehaviorSubject<boolean>(false);
  taskCalendarKey = this._config.get('process.ids.taskCalendar');

  hasFilter$ = combineLatest([
    this.taskCalendarStore.selectFetchingFilter,
    this.taskCalendarStore.selectFilter,
    this.taskCalendarStore.selectInitialFilter,
  ]).pipe(
    map(([_, filter, initialFilter]) => {
      return !isEqual(filter?.getQueryParams(), initialFilter?.getQueryParams());
    }),
    shareReplay(),
  );

  @ViewChild(TaskSearchbarComponent)
  searchbar: TaskSearchbarComponent;

  constructor(
    private taskCalendarStore: TaskCalendarStore,
    private _activatedRoute: ActivatedRoute,
    private readonly _config: Config,
  ) {
    this.taskCalendarStore.loadFilter();
  }

  ngOnInit(): void {
    this.taskCalendarStore.searchbarFocus$.pipe(takeUntil(this._onDestroy$)).subscribe(() => {
      this.searchbar?.focus();
    });

    this._activatedRoute.queryParams
      .pipe(takeUntil(this._onDestroy$), debounceTime(250))
      .subscribe(async (queryParams) => {
        const filters = UiFilter.create(await this.taskCalendarStore.selectInitialFilter.pipe(first()).toPromise());
        if (queryParams) {
          filters.fromQueryParams(queryParams);
        }
        this.taskCalendarStore.setFilter({ filters });
      });

    this.taskCalendarStore.loadItems();
  }

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