import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { InputText } from 'primeng/inputtext';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-search-input',
  templateUrl: 'search-input.component.html',
  imports: [InputText],
})
export class SearchInputComponent implements OnInit, OnDestroy {
  private searchSubject = new Subject<string>();
  private destroy$ = new Subject<void>();

  @Output() search = new EventEmitter<string>();

  ngOnInit() {
    this.searchSubject.pipe(debounceTime(300), takeUntil(this.destroy$)).subscribe((searchTerm) => {
      this.onSearch(searchTerm);
    });
  }

  onSearchInput(value: string) {
    this.searchSubject.next(value);
  }

  onSearch(searchTerm: string) {
    this.search.emit(searchTerm);
  }

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