import React, { useState, useEffect, useRef, useCallback } from 'react'

const SEARCH_API = '/api/search/artworks'
const DEBOUNCE_MS = 280

function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value)
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(id)
  }, [value, delay])
  return debounced
}

export default function SearchBar({ placeholder = 'Search artworks, artists, tags…' }) {
  const [query, setQuery]           = useState('')
  const [suggestions, setSuggestions] = useState([])
  const [loading, setLoading]       = useState(false)
  const [open, setOpen]             = useState(false)
  const inputRef   = useRef(null)
  const wrapperRef = useRef(null)
  const abortRef   = useRef(null)

  const debouncedQuery = useDebounce(query, DEBOUNCE_MS)

  const fetchSuggestions = useCallback(async (q) => {
    if (!q || q.length < 2) {
      setSuggestions([])
      setOpen(false)
      return
    }

    if (abortRef.current) abortRef.current.abort()
    abortRef.current = new AbortController()

    setLoading(true)
    try {
      const url = `${SEARCH_API}?q=${encodeURIComponent(q)}&per_page=6`
      const res = await fetch(url, { signal: abortRef.current.signal })
      if (!res.ok) return
      const json = await res.json()
      const items = json.data ?? json ?? []
      setSuggestions(Array.isArray(items) ? items.slice(0, 6) : [])
      setOpen(true)
    } catch (e) {
      if (e.name !== 'AbortError') console.error('SearchBar fetch error', e)
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchSuggestions(debouncedQuery)
  }, [debouncedQuery, fetchSuggestions])

  // Close suggestions on outside click
  useEffect(() => {
    function handler(e) {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [])

  function handleSubmit(e) {
    e.preventDefault()
    if (query.trim()) {
      window.location.href = `/search?q=${encodeURIComponent(query.trim())}`
    }
  }

  function handleSelect(item) {
    window.location.href = item.urls?.web ?? `/${item.slug ?? ''}`
  }

  function handleKeyDown(e) {
    if (e.key === 'Escape') {
      setOpen(false)
      inputRef.current?.blur()
    }
  }

  return (
    <div ref={wrapperRef} className="relative w-full">
      <form onSubmit={handleSubmit} role="search" className="relative">
        <input
          ref={inputRef}
          type="search"
          value={query}
          onChange={e => setQuery(e.target.value)}
          onFocus={() => suggestions.length > 0 && setOpen(true)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          aria-label="Search"
          autoComplete="off"
          className="w-full bg-nova-900 border border-nova-800 rounded-lg py-2.5 pl-3.5 pr-10 text-white placeholder-soft outline-none focus:border-accent transition-colors"
        />
        <button
          type="submit"
          aria-label="Submit search"
          className="absolute right-3 top-1/2 -translate-y-1/2 text-soft hover:text-accent transition-colors"
        >
          {loading
            ? <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"/></svg>
            : <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z"/></svg>
          }
        </button>
      </form>

      {open && suggestions.length > 0 && (
        <ul
          role="listbox"
          aria-label="Search suggestions"
          className="absolute top-full left-0 right-0 mt-1 bg-nova-900 border border-nova-800 rounded-xl shadow-2xl overflow-hidden z-50"
        >
          {suggestions.map((item) => (
            <li key={item.slug} role="option">
              <button
                type="button"
                onClick={() => handleSelect(item)}
                className="w-full flex items-center gap-3 px-3 py-2.5 hover:bg-white/[0.06] text-left transition-colors"
              >
                {item.thumbnail_url && (
                  <img
                    src={item.thumbnail_url}
                    alt=""
                    aria-hidden="true"
                    className="w-10 h-10 rounded object-cover shrink-0 bg-nova-900"
                    loading="lazy"
                  />
                )}
                <div className="min-w-0">
                  <div className="text-sm font-medium text-white truncate">{item.title}</div>
                  {item.author?.name && (
                    <div className="text-xs text-neutral-400 truncate">{item.author.name}</div>
                  )}
                </div>
              </button>
            </li>
          ))}
          <li className="border-t border-nova-900">
            <a
              href={`/search?q=${encodeURIComponent(query)}`}
              className="flex items-center justify-center gap-1.5 px-3 py-2 text-xs text-accent hover:text-accent/80 transition-colors"
            >
              See all results for <span className="font-semibold">"{query}"</span>
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/></svg>
            </a>
          </li>
        </ul>
      )}
    </div>
  )
}
