import { FormEvent, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { IconSearch } from './Icons'

interface Props {
  compact?: boolean
  placeholder?: string
  initialValue?: string
  /** id for the input (used by the "/" keyboard shortcut in the header). */
  inputId?: string
  /** Show the "/" keyboard hint inside the field (desktop header). */
  shortcutHint?: boolean
}

export default function SearchBar({
  compact = false,
  placeholder = 'Rechercher un produit québécois…',
  initialValue = '',
  inputId,
  shortcutHint = false,
}: Props) {
  const [value, setValue] = useState(initialValue)
  const [focused, setFocused] = useState(false)
  const navigate = useNavigate()

  function onSubmit(e: FormEvent) {
    e.preventDefault()
    const q = value.trim()
    navigate(q ? `/produits?q=${encodeURIComponent(q)}` : '/produits')
  }

  return (
    <form
      className={compact ? 'searchbar searchbar-compact' : 'searchbar'}
      onSubmit={onSubmit}
      role="search"
    >
      <div className="searchbar-field">
        <span className="searchbar-icon" aria-hidden="true">
          <IconSearch size={compact ? 16 : 18} />
        </span>
        <input
          id={inputId}
          type="search"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          placeholder={placeholder}
          aria-label="Rechercher"
          enterKeyHint="search"
        />
        {shortcutHint && !focused && value === '' && (
          <kbd className="searchbar-kbd" aria-hidden="true">
            /
          </kbd>
        )}
      </div>
      {!compact && (
        <button type="submit" aria-label="Lancer la recherche">
          Rechercher
        </button>
      )}
    </form>
  )
}
