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

const ARTWORKS_API = '/api/search/artworks'
const TAGS_API     = '/api/tags/search'
const USERS_API    = '/api/search/users'
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
}

const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPod|iPad/.test(navigator.platform)

export default function SearchBar({ placeholder = 'Search artworks, artists, tags\u2026' }) {
  const [phase, setPhase]       = useState('idle')   // idle | opening | open | closing
  const [query, setQuery]       = useState('')
  const [artworks, setArtworks] = useState([])
  const [tags, setTags]         = useState([])
  const [users, setUsers]       = useState([])
  const [loading, setLoading]   = useState(false)
  const [open, setOpen]         = useState(false)
  const [activeIdx, setActiveIdx] = useState(-1)

  const inputRef      = useRef(null)
  const wrapperRef    = useRef(null)
  const abortRef      = useRef(null)
  const openTimerRef  = useRef(null)
  const closeTimerRef = useRef(null)

  const debouncedQuery = useDebounce(query, DEBOUNCE_MS)
  const isExpanded     = phase === 'opening' || phase === 'open'

  // flat list of navigable items: artworks → users → tags
  const allItems = [
    ...artworks.map(a => ({ type: 'artwork', ...a })),
    ...users.map(u => ({ type: 'user', ...u })),
    ...tags.map(t => ({ type: 'tag', ...t })),
  ]

  // ── expand / collapse ────────────────────────────────────────────────────
  function expand() {
    clearTimeout(closeTimerRef.current)
    setPhase('opening')
    openTimerRef.current = setTimeout(() => {
      setPhase('open')
      inputRef.current?.focus()
    }, 80)
  }

  function collapse() {
    clearTimeout(openTimerRef.current)
    setPhase('closing')
    setOpen(false)
    setActiveIdx(-1)
    closeTimerRef.current = setTimeout(() => {
      setPhase('idle')
      setQuery('')
      setArtworks([])
      setTags([])
      setUsers([])
    }, 160)
  }

  // ── Ctrl/Cmd+K ───────────────────────────────────────────────────────────
  useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); expand() }
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [])

  // ── outside click ────────────────────────────────────────────────────────
  useEffect(() => {
    function onMouse(e) {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) collapse()
    }
    document.addEventListener('mousedown', onMouse)
    return () => document.removeEventListener('mousedown', onMouse)
  }, [])

  // ── fetch (parallel artworks + tags) ────────────────────────────────────
  const fetchSuggestions = useCallback(async (q) => {
    const bare = q?.replace(/^@+/, '') ?? ''
    if (!bare || bare.length < 2) {
      setArtworks([]); setTags([]); setUsers([]); setOpen(false); return
    }
    if (abortRef.current) abortRef.current.abort()
    abortRef.current = new AbortController()
    const sig = abortRef.current.signal
    setLoading(true)
    try {
      const isAtMention = q.startsWith('@')
      // if user typed @foo: emphasise users (4 slots) and skip artworks
      const fetchArt = isAtMention
        ? Promise.resolve(null)
        : fetch(`${ARTWORKS_API}?q=${encodeURIComponent(bare)}&per_page=4`, { signal: sig })
      const fetchUsers = fetch(`${USERS_API}?q=${encodeURIComponent(q)}&per_page=4`, { signal: sig })
      const fetchTags  = isAtMention
        ? Promise.resolve(null)
        : fetch(`${TAGS_API}?q=${encodeURIComponent(bare)}&per_page=3`, { signal: sig })
      const [artRes, userRes, tagRes] = await Promise.all([fetchArt, fetchUsers, fetchTags])
      const artJson  = artRes  && artRes.ok  ? await artRes.json()  : {}
      const userJson = userRes && userRes.ok ? await userRes.json() : {}
      const tagJson  = tagRes  && tagRes.ok  ? await tagRes.json()  : {}
      const artItems  = Array.isArray(artJson.data  ?? artJson)  ? (artJson.data  ?? artJson).slice(0, 4)  : []
      const userItems = Array.isArray(userJson.data ?? userJson) ? (userJson.data ?? userJson).slice(0, 4) : []
      const tagItems  = Array.isArray(tagJson.data  ?? tagJson)  ? (tagJson.data  ?? tagJson).slice(0, 3)  : []
      setArtworks(artItems)
      setUsers(userItems)
      setTags(tagItems)
      setActiveIdx(-1)
      setOpen(artItems.length > 0 || userItems.length > 0 || tagItems.length > 0)
    } catch (e) {
      if (e.name !== 'AbortError') console.error('SearchBar fetch error', e)
    } finally {
      setLoading(false)
    }
  }, [])

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

  // ── navigation helpers ───────────────────────────────────────────────────
  function navigate(item) {
    if (item.type === 'artwork') window.location.href = item.urls?.web ?? `/${item.slug ?? ''}`
    else if (item.type === 'user') window.location.href = item.profile_url ?? `/@${item.username}`
    else window.location.href = `/tags/${item.slug ?? item.name}`
  }

  function handleSubmit(e) {
    e.preventDefault()
    if (activeIdx >= 0 && allItems[activeIdx]) { navigate(allItems[activeIdx]); return }
    if (query.trim()) window.location.href = `/search?q=${encodeURIComponent(query.trim())}`
  }

  function handleKeyDown(e) {
    if (e.key === 'Escape') { collapse(); return }
    if (!open || allItems.length === 0) return
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      setActiveIdx(i => (i + 1) % allItems.length)
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      setActiveIdx(i => (i <= 0 ? allItems.length - 1 : i - 1))
    } else if (e.key === 'Enter' && activeIdx >= 0) {
      e.preventDefault()
      navigate(allItems[activeIdx])
    }
  }

  // ── widths / opacities ───────────────────────────────────────────────────
  const pillOpacity = phase === 'idle' ? 1 : 0
  const formOpacity = phase === 'open'  ? 1 : 0

  return (
    <div
      ref={wrapperRef}
      style={{
        position:   'relative',
        height:     '40px',
        width:      isExpanded ? '100%'  : '168px',
        maxWidth:   isExpanded ? '560px' : '168px',
        transition: 'width 340ms cubic-bezier(0.16,1,0.3,1), max-width 340ms cubic-bezier(0.16,1,0.3,1)',
      }}
    >
      {/* ── COLLAPSED PILL ── */}
      <button
        type="button"
        onClick={expand}
        aria-label="Open search"
        style={{ position: 'absolute', inset: 0, opacity: pillOpacity, pointerEvents: phase === 'idle' ? 'auto' : 'none', transition: 'opacity 120ms ease' }}
        className="w-full h-full flex items-center gap-2.5 px-3.5 rounded-lg
                   bg-white/[0.05] border border-white/[0.09]
                   text-soft hover:bg-white/[0.1] hover:border-white/20 hover:text-white transition-colors"
      >
        <svg className="w-4 h-4 shrink-0" 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>
        <span className="text-sm flex-1 text-left truncate">Search\u2026</span>
        <kbd className="shrink-0 inline-flex items-center gap-0.5 text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-white/[0.06] border border-white/[0.10] text-white/30">
          {isMac ? '\u2318' : 'Ctrl'}K
        </kbd>
      </button>

      {/* ── EXPANDED FORM ── */}
      <form
        onSubmit={handleSubmit}
        role="search"
        style={{ position: 'absolute', inset: 0, opacity: formOpacity, pointerEvents: phase === 'open' ? 'auto' : 'none', transition: 'opacity 180ms ease 60ms' }}
      >
        <div className="relative h-full">
          <svg className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-soft pointer-events-none"
               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>
          <input
            ref={inputRef}
            type="search"
            value={query}
            onChange={e => { setQuery(e.target.value); setActiveIdx(-1) }}
            onFocus={() => (artworks.length > 0 || tags.length > 0) && setOpen(true)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            aria-label="Search"
            aria-autocomplete="list"
            aria-controls="sb-suggestions"
            aria-activedescendant={activeIdx >= 0 ? `sb-item-${activeIdx}` : undefined}
            autoComplete="off"
            className="w-full h-full bg-white/[0.06] border border-white/[0.12] rounded-lg
                       py-0 pl-10 pr-16 text-sm text-white placeholder-soft outline-none
                       focus:border-accent focus:ring-1 focus:ring-accent/30 transition-colors"
          />
          <div className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1.5">
            {loading && (
              <svg className="w-3.5 h-3.5 animate-spin text-soft" 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>
            )}
            <kbd className="text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-white/[0.06] border border-white/[0.10] text-white/30 pointer-events-none select-none">Esc</kbd>
            <button type="button" onClick={collapse} aria-label="Close search"
              className="w-5 h-5 flex items-center justify-center rounded-md text-white/30 hover:text-white hover:bg-white/10 transition-colors">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5">
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/>
              </svg>
            </button>
          </div>
        </div>
      </form>

      {/* ── SUGGESTIONS DROPDOWN ── */}
      {open && (artworks.length > 0 || tags.length > 0) && (
        <ul
          id="sb-suggestions"
          role="listbox"
          aria-label="Search suggestions"
          className="absolute top-full left-0 right-0 mt-1.5 bg-[#151820] border border-white/[0.10] rounded-xl shadow-2xl overflow-hidden z-50"
          style={{ opacity: formOpacity, transition: 'opacity 180ms ease 60ms' }}
        >
          {/* Artworks section */}
          {artworks.length > 0 && (
            <>
              <li role="presentation" className="px-3 pt-2.5 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/30 select-none">Artworks</li>
              {artworks.map((item, i) => (
                <li key={item.slug ?? i} role="option" id={`sb-item-${i}`} aria-selected={activeIdx === i}>
                  <button type="button" onClick={() => navigate({ type: 'artwork', ...item })}
                    className={`w-full flex items-center gap-3 px-3 py-2.5 text-left transition-colors ${activeIdx === i ? 'bg-white/[0.09]' : 'hover:bg-white/[0.06]'}`}>
                    {item.thumbnail_url && (
                      <img src={item.thumbnail_url} alt="" aria-hidden="true"
                           className="w-9 h-9 rounded-lg object-cover shrink-0" 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>
                    <svg className="w-3.5 h-3.5 text-white/20 ml-auto shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/>
                    </svg>
                  </button>
                </li>
              ))}
            </>
          )}

          {/* Users / Creators section */}
          {users.length > 0 && (
            <>
              <li role="presentation" className={`px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/30 select-none ${artworks.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2.5'}`}>Creators</li>
              {users.map((user, j) => {
                const flatIdx = artworks.length + j
                return (
                  <li key={user.username} role="option" id={`sb-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                    <button type="button" onClick={() => navigate({ type: 'user', ...user })}
                      className={`w-full flex items-center gap-3 px-3 py-2 text-left transition-colors ${activeIdx === flatIdx ? 'bg-white/[0.09]' : 'hover:bg-white/[0.06]'}`}>
                      <img src={user.avatar_url} alt="" aria-hidden="true"
                           className="w-9 h-9 rounded-full object-cover shrink-0 bg-white/[0.04] border border-white/[0.08]" loading="lazy" />
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-white truncate">@{user.username}</div>
                        {user.uploads > 0 && <div className="text-xs text-neutral-400">{user.uploads.toLocaleString()} upload{user.uploads !== 1 ? 's' : ''}</div>}
                      </div>
                    </button>
                  </li>
                )
              })}
            </>
          )}

          {/* Tags section */}
          {tags.length > 0 && (
            <>
              <li role="presentation" className={`px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-white/30 select-none ${artworks.length > 0 || users.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2.5'}`}>Tags</li>
              {tags.map((tag, j) => {
                const flatIdx = artworks.length + users.length + j
                return (
                  <li key={tag.slug ?? tag.name ?? j} role="option" id={`sb-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                    <button type="button" onClick={() => navigate({ type: 'tag', ...tag })}
                      className={`w-full flex items-center gap-3 px-3 py-2 text-left transition-colors ${activeIdx === flatIdx ? 'bg-white/[0.09]' : 'hover:bg-white/[0.06]'}`}>
                      <span className="w-9 h-9 rounded-lg bg-white/[0.04] border border-white/[0.07] inline-flex items-center justify-center shrink-0">
                        <svg className="w-3.5 h-3.5 text-white/40" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"/>
                        </svg>
                      </span>
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-white truncate">#{tag.name ?? tag.slug}</div>
                        {tag.artworks_count != null && <div className="text-xs text-neutral-400">{tag.artworks_count.toLocaleString()} artworks</div>}
                      </div>
                    </button>
                  </li>
                )
              })}
            </>
          )}

          {/* See all footer */}
          <li role="presentation" className="border-t border-white/[0.06]">
            <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 h-3" 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>
  )
}
