'use client'

import { FormEvent, useState } from 'react'
import { useRouter } from 'next/navigation'
import Image from 'next/image'
import SearchIcon from './search.svg'
import styles from './styles.module.scss'

type MenuSearchProps = {
  onSubmitted?: () => void
}

export const MenuSearch = ({ onSubmitted }: MenuSearchProps) => {
  const router = useRouter()
  const [value, setValue] = useState('')

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const q = value.trim()
    if (!q) return
    router.push(`/suche?q=${encodeURIComponent(q)}`)
    onSubmitted?.()
  }

  return (
    <form className={styles.search} onSubmit={handleSubmit} role="search">
      <input
        type="search"
        name="q"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Suchen..."
        aria-label="Suche"
        className={styles.searchInput}
      />
      <button type="submit" className={styles.searchButton} aria-label="Suchen">
        <Image src={SearchIcon} width={20} height={20} alt="" />
      </button>
    </form>
  )
}
