import { FormEvent, useEffect, useRef, useState } from 'react'
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
import { IconClose, IconGrid, IconHome, IconSearch, IconStore } from './Icons'

/**
 * Mobile bottom tab bar (<768px) — Accueil, Produits, Boutiques, Recherche.
 * "Recherche" opens a full-screen search overlay with an autofocused input.
 */
export default function BottomNav() {
  const [searchOpen, setSearchOpen] = useState(false)
  const [query, setQuery] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)
  const navigate = useNavigate()
  const location = useLocation()

  // Close the overlay on navigation.
  useEffect(() => {
    setSearchOpen(false)
  }, [location.pathname, location.search])

  // Autofocus + scroll lock while the overlay is open.
  useEffect(() => {
    if (!searchOpen) return
    document.body.style.overflow = 'hidden'
    const t = window.setTimeout(() => inputRef.current?.focus(), 60)
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setSearchOpen(false)
    }
    window.addEventListener('keydown', onKey)
    return () => {
      document.body.style.overflow = ''
      window.clearTimeout(t)
      window.removeEventListener('keydown', onKey)
    }
  }, [searchOpen])

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

  return (
    <>
      {searchOpen && (
        <div
          className="search-overlay"
          role="dialog"
          aria-modal="true"
          aria-label="Recherche"
        >
          <div className="search-overlay-bar">
            <form className="search-overlay-form" onSubmit={onSubmit} role="search">
              <span className="search-overlay-icon" aria-hidden="true">
                <IconSearch size={18} />
              </span>
              <input
                ref={inputRef}
                type="search"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Rechercher un produit québécois…"
                aria-label="Rechercher"
                enterKeyHint="search"
              />
            </form>
            <button
              type="button"
              className="search-overlay-close"
              onClick={() => setSearchOpen(false)}
              aria-label="Fermer la recherche"
            >
              <IconClose size={22} />
            </button>
          </div>
          <p className="search-overlay-hint">
            Produits fabriqués, conçus et vendus au Québec.
          </p>
        </div>
      )}

      <nav className="bottom-nav" aria-label="Navigation mobile">
        <NavLink to="/" end className="bottom-nav-item">
          <IconHome size={22} />
          <span>Accueil</span>
        </NavLink>
        <NavLink to="/produits" className="bottom-nav-item">
          <IconGrid size={22} />
          <span>Produits</span>
        </NavLink>
        <NavLink to="/boutiques" className="bottom-nav-item">
          <IconStore size={22} />
          <span>Boutiques</span>
        </NavLink>
        <button
          type="button"
          className={
            searchOpen ? 'bottom-nav-item active' : 'bottom-nav-item'
          }
          onClick={() => setSearchOpen(true)}
          aria-label="Ouvrir la recherche"
        >
          <IconSearch size={22} />
          <span>Recherche</span>
        </button>
      </nav>
    </>
  )
}
