import {
  ChangeDetectionStrategy,
  Component,
  inject,
  input,
  ViewEncapsulation,
} from '@angular/core';
import { isaActionClose } from '@isa/icons';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { UiSearchBarComponent } from './search-bar.component';
import { asapScheduler } from 'rxjs';

@Component({
  selector: 'ui-search-bar-clear',
  template:
    '<ng-icon name="isaActionClose" data-which="clear-search-icon"></ng-icon>',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [NgIconComponent],
  providers: [provideIcons({ isaActionClose })],
  host: {
    '[class]': "['ui-search-bar__action__close']",
    '(click)': 'reset(null)',
  },
})
export class UiSearchBarClearComponent {
  private searchBar = inject(UiSearchBarComponent);

  value = input<unknown>();

  reset(value?: unknown): void {
    const resetValue = value ?? this.value();
    this.searchBar.inputControl().reset(resetValue);
    asapScheduler.schedule(() => {
      this.searchBar.inputControlElementRef().nativeElement.focus();
    });
  }
}
