import {
  Component,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  AfterViewInit,
  OnDestroy,
  TemplateRef
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'ccl-searchbar',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './searchbar.html',
  styleUrls: ['./searchbar.css'],
})
export class SearchbarComponent implements AfterViewInit, OnDestroy {
  @Input() placeholder = 'Search...';
  @Input() value = '';
  @Input() debounce = 300;
  @Input() clearable = true;
  @Input() disabled = false;
  @Input() showIcon = true;
  @Input() searchIcon?: TemplateRef<unknown>;
  @Input() clearIcon?: TemplateRef<unknown>;

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

  @ViewChild('inputEl') inputEl!: ElementRef<HTMLInputElement>;

  private timeoutId: any;

  ngAfterViewInit() {
    // ViewChild is now available, no additional setup needed
  }

  ngOnDestroy() {
    clearTimeout(this.timeoutId);
  }

  handleInput(event: Event) {
    const newValue = (event.target as HTMLInputElement).value;
    this.value = newValue;
    clearTimeout(this.timeoutId);

    if (this.debounce > 0) {
      this.timeoutId = setTimeout(() => {
        this.onSearch.emit(this.value);
      }, this.debounce);
    } else {
      this.onSearch.emit(this.value);
    }
  }

  handleEnter() {
    clearTimeout(this.timeoutId);
    this.onSearch.emit(this.value);
  }

  clear() {
    this.value = '';
    this.onSearch.emit(this.value);
    if (this.inputEl?.nativeElement) {
      this.inputEl.nativeElement.focus();
    }
  }
}
