import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  inject,
  input,
  viewChild,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaActionClose } from '@isa/icons';
import { logger } from '@isa/core/logging';
import { DROPDOWN_HOST, DropdownHost } from './dropdown-host';

/**
 * A filter input component for use within a DropdownButtonComponent.
 * Renders as a sticky input at the top of the options panel.
 *
 * @example
 * ```html
 * <ui-dropdown [(ngModel)]="selected">
 *   <ui-dropdown-filter placeholder="Search..."></ui-dropdown-filter>
 *   <ui-dropdown-option [value]="'opt1'">Option 1</ui-dropdown-option>
 *   <ui-dropdown-option [value]="'opt2'">Option 2</ui-dropdown-option>
 * </ui-dropdown>
 * ```
 */
@Component({
  selector: 'ui-dropdown-filter',
  templateUrl: './dropdown-filter.component.html',
  styles: `
    :host {
      display: contents;
    }
  `,
  imports: [FormsModule, NgIconComponent],
  providers: [provideIcons({ isaActionClose })],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DropdownFilterComponent {
  #logger = logger({ component: 'DropdownFilterComponent' });

  host = inject(DROPDOWN_HOST, { host: true }) as DropdownHost<unknown>;

  filterInput = viewChild<ElementRef<HTMLInputElement>>('filterInput');

  /** Placeholder text for the filter input */
  placeholder = input<string>('Suchen...');

  onFilterChange(value: string): void {
    this.#logger.debug('Filter changed', () => ({ value }));
    this.host.filter.set(value);
  }

  clearFilter(event: Event): void {
    event.stopPropagation();
    this.#logger.debug('Filter cleared');
    this.host.filter.set('');
  }

  /** Forward arrow key events to the dropdown's keyManager for navigation */
  onArrowKey(event: KeyboardEvent): void {
    event.preventDefault();
    this.host.onKeydown(event);
  }

  /** Handle enter key to select the active option */
  onEnterKey(event: KeyboardEvent): void {
    event.preventDefault();
    event.stopPropagation();
    this.host.selectActiveItem();
    this.host.close();
  }

  /** Focus the filter input. Called by parent dropdown on open. */
  focus(): void {
    this.filterInput()?.nativeElement.focus();
  }
}
