<script lang="ts">
  import { Input } from '$lib/components/ui/input'
  import SearchIcon from '@lucide/svelte/icons/search'
  import XIcon from '@lucide/svelte/icons/x'
  import { debounce } from '$lib/utils'

  let {
    value = '',
    placeholder = 'Search...',
    class: className,
    onSearch
  }: {
    value?: string
    placeholder?: string
    class?: string
    onSearch?: (q: string) => void
  } = $props()

  let inputVal = $state('')

  const debouncedSearch = debounce((q: string) => {
    onSearch?.(q)
  }, 200)

  function handleInput(e: Event) {
    const target = e.target as HTMLInputElement
    inputVal = target.value
    debouncedSearch(inputVal)
  }

  function clear() {
    inputVal = ''
    onSearch?.('')
  }
</script>

<div class={['relative', className].filter(Boolean).join(' ')}>
  <SearchIcon class="absolute left-2 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
  <Input
    type="text"
    {placeholder}
    value={inputVal}
    oninput={handleInput}
    class="h-8 pl-8 pr-8 text-xs"
  />
  {#if inputVal}
    <button
      type="button"
      class="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
      onclick={clear}
    >
      <XIcon class="size-3" />
    </button>
  {/if}
</div>
