import { AfterViewChecked, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { debounceTime, map } from 'rxjs/operators';
import { ActivatedRoute, Router } from '@angular/router';
import { UntypedFormControl } from '@angular/forms';
import { SearchService } from '@shared/ui-api/search.service';
import { ISearchConfig } from '@shared/ui-api/interfaces/route-config/search-config';
import { RouteHelper } from '@shared/ui-api/route-helper';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-search-box',
  templateUrl: './search-box.component.html',
  styleUrls: ['./search-box.component.scss']
})
export class SearchBoxComponent implements OnInit, AfterViewChecked {
  @Input() searchConfig: ISearchConfig;
  @ViewChild('mobileSearchInput') mobileSearchInput: ElementRef;
  searchText: UntypedFormControl = new UntypedFormControl('searchText');
  showMobileInput = false;
  searchPlaceholder = $localize`Search ...`;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private searchService: SearchService,
    private config: ConfigService,
  ) { }

  ngOnInit() {
    this.setSearchText();

    this.searchText.valueChanges.pipe(
      map(() => this.searchText.value as string),
      debounceTime(1000),
    ).subscribe(searchText => {
      if (searchText && searchText.length >= this.config.current.settings.minSearchLength) {
        this.searchService.search(searchText, this.searchConfig.resetQueryParams);
      } else if (typeof searchText === 'string' && searchText.length === 0) {
        this.clearSearch();
      }
    });
  }

  setSearchText() {
    const routeSnapshot = new RouteHelper(this.route).getFinalRoute().snapshot;
    if (routeSnapshot.queryParams.search) {
      this.searchText.setValue(routeSnapshot.queryParams.search, { emitEvent: false });
    } else {
      this.searchText.setValue(undefined, { emitEvent: false });
    }
  }

  clearSearch() {
    this.searchText.setValue(undefined, { emitEvent: false });
    this.searchService.search(undefined);
  }

  ngAfterViewChecked() {
    if (this.showMobileInput) {
      this.mobileSearchInput.nativeElement.focus();
    }
  }

  switchShowMobileInput() {
    this.showMobileInput = !this.showMobileInput;
  }
}
