import { Component, OnInit, OnDestroy, ViewChild, ChangeDetectorRef } from '@angular/core';
import { UntypedFormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Breadcrumb, BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { UiAutofocusDirective } from '@ui/common';
import { UiFilter } from '@ui/filter';
import { isEqual } from 'lodash';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { TaskCalendarStore } from '../../task-calendar.store';

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

  control = new UntypedFormControl('', [Validators.minLength(3)]);

  @ViewChild(UiAutofocusDirective)
  autofocus: UiAutofocusDirective;

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

  getControlValueFromQuery() {
    return this._activatedRoute.snapshot?.queryParams?.main_qs ?? '';
  }

  ngOnInit(): void {
    this.control.patchValue(this.getControlValueFromQuery());

    this.control.valueChanges.pipe(takeUntil(this._onDestroy$), debounceTime(250)).subscribe((value) => {
      this.setValueInFilter(value);
      this._cdr.markForCheck();
    });

    this.taskCalendarStore
      .select((s) => s.filter)
      .pipe(takeUntil(this._onDestroy$))
      .subscribe((filter) => {
        const value = filter?.input?.find((_) => true)?.input?.find((_) => true)?.value ?? '';
        if (value !== this.control.value) {
          this.control.patchValue(value);
          this._cdr.markForCheck();
        }
      });
  }

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

  setValueInFilter(value: string): void {
    const filter = UiFilter.create(this.taskCalendarStore.filter);
    filter.input
      ?.find((_) => true)
      ?.input?.find((_) => true)
      ?.setValue(value);

    this.taskCalendarStore.setFilter({ filters: filter });
  }

  clearSearch() {
    this.control.patchValue('');
    this.setValueInFilter('');
  }

  searchTasks() {
    if (this.control.valid) {
      this.setValueInFilter(this.control.value);
      const filter = UiFilter.create(this.taskCalendarStore.filter);
      const params = { ...filter?.getQueryParams() };
      this.updateBreadcrumbs(params);
      this.navigate('/filiale/task-calendar/search', params);

      // 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(filter.getQueryParams(), this._activatedRoute.snapshot.queryParams)) {
        this.taskCalendarStore.search({ clear: true });
      }
    }
  }

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

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

  focus() {
    this.autofocus?.focus();
  }
}
