import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  input,
  output,
  signal,
  OnDestroy,
} from '@angular/core';

@Component({
  selector: 'app-search-bar',
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './search-bar.html',
  styleUrl: './search-bar.css',
})
export class SearchBar implements OnDestroy {
  placeholder = input('Rechercher…');
  debounceMs = input<number>(300); // Default 300ms debounce

  // Local signal to hold the current query string in the input field
  searchTerm = signal('');

  // Output event to notify parent component of the search query
  search = output<string>();

  private debounceTimer: ReturnType<typeof setTimeout> | null = null;

  // Handles input change, updates the signal, and emits the new search term with debounce
  handleInput(value: string) {
    this.searchTerm.set(value);
    this.debounceEmit();
  }

  private debounceEmit() {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
    this.debounceTimer = setTimeout(() => {
    this.emitSearch();
    }, this.debounceMs());
  }

  emitSearch() {
    this.search.emit(this.searchTerm().trim());
  }

  reset() {
    this.searchTerm.set('');
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
    this.emitSearch();
  }

  ngOnDestroy() {
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer);
    }
  }
}
