import { ChangeDetectionStrategy, Component, EventEmitter, HostListener, Input, Output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SearchSuggestion } from '../../models/search.model';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { IconComponent } from '../../../../shared/ui/icon/icon.component';
import { TrendingSearchesComponent } from '../trending-searches/trending-searches.component';

@Component({
  selector: 'app-search-bar',
  standalone: true,
  imports: [FormsModule, TranslatePipe, IconComponent, TrendingSearchesComponent],
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SearchBarComponent {
  @Input() query = '';
  @Input() loading = false;
  @Input() suggestions: SearchSuggestion[] = [];
  @Input() recentSearches: string[] = [];
  @Input() popularSearches: string[] = [];
  @Input() searchHistory: string[] = [];
  @Input() noResults = false;

  @Output() queryChange = new EventEmitter<string>();
  @Output() searchSubmit = new EventEmitter<string>();
  @Output() suggestionSelected = new EventEmitter<SearchSuggestion>();
  @Output() recentSelected = new EventEmitter<string>();
  @Output() historyCleared = new EventEmitter<void>();

  readonly activeSuggestionIndex = signal(-1);
  readonly focused = signal(false);
  readonly mobileOverlayOpen = signal(false);

  @HostListener('window:resize')
  onResize(): void {
    if (!this.isMobile()) {
      this.mobileOverlayOpen.set(false);
    }
  }

  onSubmit(event: Event): void {
    event.preventDefault();

    const active = this.suggestions[this.activeSuggestionIndex()];
    if (active) {
      this.selectSuggestion(active);
      return;
    }

    this.searchSubmit.emit(this.query.trim());
    this.mobileOverlayOpen.set(false);
  }

  onQueryInput(value: string): void {
    this.queryChange.emit(value);
    this.activeSuggestionIndex.set(-1);
  }

  onFocus(): void {
    this.focused.set(true);
    if (this.isMobile()) {
      this.mobileOverlayOpen.set(true);
    }
  }

  onBlur(): void {
    this.focused.set(false);
  }

  selectSuggestion(suggestion: SearchSuggestion): void {
    this.suggestionSelected.emit(suggestion);
    this.activeSuggestionIndex.set(-1);
    this.mobileOverlayOpen.set(false);
  }

  clearQuery(): void {
    this.queryChange.emit('');
    this.searchSubmit.emit('');
    this.activeSuggestionIndex.set(-1);
  }

  closeOverlay(): void {
    this.mobileOverlayOpen.set(false);
  }

  onKeydown(event: KeyboardEvent): void {
    if (event.key === 'Escape') {
      event.preventDefault();
      this.activeSuggestionIndex.set(-1);
      this.mobileOverlayOpen.set(false);
      return;
    }

    if (this.suggestions.length === 0) {
      return;
    }

    if (event.key === 'ArrowDown') {
      event.preventDefault();
      this.activeSuggestionIndex.set(Math.min(this.suggestions.length - 1, this.activeSuggestionIndex() + 1));
      return;
    }

    if (event.key === 'ArrowUp') {
      event.preventDefault();
      this.activeSuggestionIndex.set(Math.max(-1, this.activeSuggestionIndex() - 1));
      return;
    }

    if (event.key === 'Enter' && this.activeSuggestionIndex() >= 0) {
      event.preventDefault();
      const active = this.suggestions[this.activeSuggestionIndex()];
      this.selectSuggestion(active);
    }
  }

  onRecentSelected(value: string): void {
    this.recentSelected.emit(value);
    this.activeSuggestionIndex.set(-1);
    this.mobileOverlayOpen.set(false);
  }

  suggestionLabel(item: SearchSuggestion): string {
    return item.subtitle ? `${item.title} · ${item.subtitle}` : item.title;
  }

  private isMobile(): boolean {
    return typeof window !== 'undefined' && window.innerWidth <= 767;
  }
}
