import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Search, Close } from '../icons'

/** Full-width search overlay opened from the top bar. */
export default function SearchOverlay({ open, onClose }) {
  const [q, setQ] = useState('')
  const inputRef = useRef(null)
  const navigate = useNavigate()

  useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50)
  }, [open])

  useEffect(() => {
    const onKey = (e) => e.key === 'Escape' && onClose()
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onClose])

  if (!open) return null

  const submit = (e) => {
    e.preventDefault()
    const term = q.trim()
    if (!term) return
    navigate(`/search?q=${encodeURIComponent(term)}`)
    onClose()
    setQ('')
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div
        className="mx-auto mt-24 max-w-2xl px-4"
        onClick={(e) => e.stopPropagation()}
      >
        <form
          onSubmit={submit}
          className="flex items-center gap-3 rounded-2xl bg-white p-3 shadow-2xl dark:bg-gray-900"
        >
          <Search className="ml-2 text-gray-400" width={22} height={22} />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search videos, categories, tags…"
            className="flex-1 bg-transparent text-lg outline-none placeholder:text-gray-400"
          />
          <button
            type="button"
            onClick={onClose}
            className="rounded-lg p-2 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800"
          >
            <Close />
          </button>
        </form>
        <p className="mt-3 text-center text-sm text-white/70">
          Press Enter to search · Esc to close
        </p>
      </div>
    </div>
  )
}
