import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';

@Component({
  selector: 'app-search-box',
  templateUrl: './search-box.component.html',
  styleUrls: ['./search-box.component.scss'],
})
export class SearchBoxComponent {
  @Input() value = '';
  @Input() placeholder = 'Buscar';
  @Input() results: { id: number; label: string }[] = [];

  @Output() valueChange = new EventEmitter<string>();
  @Output() onSearch = new EventEmitter<string>();
  @Output() onDebounceSearch = new EventEmitter<string>();
  @Output() onChooseResult = new EventEmitter<number>();

  maxResults = 5;
  debounceTime = 500;

  searchDebounced = new Subject<string>();

  constructor() {
    this.searchDebounced
      .pipe(distinctUntilChanged(), debounceTime(this.debounceTime))
      .subscribe((value) => this.onDebounceSearch.emit(value));
  }

  handleValueChange(ev: Event) {
    const value = (ev.target as HTMLInputElement).value;

    this.searchDebounced.next(value.trim());
    this.valueChange.emit(value);
  }

  handleChoose(resultId: number) {
    const option = this.results.find((r) => r.id === resultId);

    if (option) this.onSearch.emit(option.label);
    this.onChooseResult.emit(resultId);
  }

  handleSearch() {
    this.onSearch.emit(this.value);
  }
}
