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

const ARTWORKS_API = '/api/search/artworks'
const GROUPS_API   = '/api/search/groups'
const TAGS_API     = '/api/tags/search'
const USERS_API    = '/api/search/users'
const DEBOUNCE_MS  = 300

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, groups, artists, tags\u2026', initialIntent = null }) {
  const [phase, setPhase]       = useState('idle')   // idle | opening | open | closing
  const [query, setQuery]       = useState('')
  const [artworks, setArtworks] = useState([])
  const [groups, setGroups]     = 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 [mobileOverlayPhase, setMobileOverlayPhase] = useState('closed') // closed | opening | open | closing

  const inputRef      = useRef(null)
  const mobileInputRef = useRef(null)
  const wrapperRef    = useRef(null)
  const abortRef      = useRef(null)
  const openTimerRef  = useRef(null)
  const closeTimerRef = useRef(null)
  const mobileOpenTimerRef = useRef(null)
  const mobileCloseTimerRef = useRef(null)
  const initialIntentHandledRef = useRef(false)

  const debouncedQuery = useDebounce(query, DEBOUNCE_MS)
  const isExpanded     = phase === 'opening' || phase === 'open'
  const isMobileOverlayVisible = mobileOverlayPhase !== 'closed'
  const hasSuggestions = artworks.length > 0 || groups.length > 0 || users.length > 0 || tags.length > 0
  const suggestionListId = open && hasSuggestions ? 'sb-suggestions' : undefined

  // flat list of navigable items: artworks → groups → users → tags
  const allItems = [
    ...artworks.map(a => ({ type: 'artwork', ...a })),
    ...groups.map(g => ({ type: 'group', ...g })),
    ...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() {
    if (phase === 'idle' || phase === 'closing') return
    clearTimeout(openTimerRef.current)
    setPhase('closing')
    setOpen(false)
    setActiveIdx(-1)
    closeTimerRef.current = setTimeout(() => {
      setPhase('idle')
      setQuery('')
      setArtworks([])
      setGroups([])
      setTags([])
      setUsers([])
    }, 160)
  }

  function openMobileOverlay() {
    clearTimeout(mobileCloseTimerRef.current)
    setMobileOverlayPhase('opening')
    mobileOpenTimerRef.current = setTimeout(() => {
      setMobileOverlayPhase('open')
      mobileInputRef.current?.focus()
    }, 20)
  }

  function closeMobileOverlay() {
    if (mobileOverlayPhase === 'closed' || mobileOverlayPhase === 'closing') return
    clearTimeout(mobileOpenTimerRef.current)
    setMobileOverlayPhase('closing')
    clearTimeout(mobileCloseTimerRef.current)
    mobileCloseTimerRef.current = setTimeout(() => {
      setMobileOverlayPhase('closed')
      setQuery('')
      setActiveIdx(-1)
      setOpen(false)
      setArtworks([])
      setGroups([])
      setTags([])
      setUsers([])
    }, 150)
  }

  // ── 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)
  }, [])

  useEffect(() => {
    if (initialIntentHandledRef.current || !initialIntent) {
      return
    }

    initialIntentHandledRef.current = true

    if (initialIntent === 'mobile') {
      openMobileOverlay()
      return
    }

    if (initialIntent === 'desktop') {
      expand()
    }
  }, [initialIntent])

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

  useEffect(() => {
    if (!isMobileOverlayVisible) {
      document.body.style.overflow = ''
      return
    }
    document.body.style.overflow = 'hidden'
    return () => {
      document.body.style.overflow = ''
    }
  }, [isMobileOverlayVisible])

  useEffect(() => {
    if (!isMobileOverlayVisible) return
    function onEscape(e) {
      if (e.key === 'Escape') closeMobileOverlay()
    }
    document.addEventListener('keydown', onEscape)
    return () => document.removeEventListener('keydown', onEscape)
  }, [isMobileOverlayVisible, mobileOverlayPhase])

  useEffect(() => {
    return () => {
      clearTimeout(mobileOpenTimerRef.current)
      clearTimeout(mobileCloseTimerRef.current)
    }
  }, [])

  // ── fetch (parallel artworks + tags) ────────────────────────────────────
  const fetchSuggestions = useCallback(async (q) => {
    const bare = q?.replace(/^@+/, '') ?? ''
    if (!bare || bare.length < 2) {
      setArtworks([]); setGroups([]); 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 fetchGroups = isAtMention
        ? Promise.resolve(null)
        : fetch(`${GROUPS_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, groupRes, userRes, tagRes] = await Promise.all([fetchArt, fetchGroups, fetchUsers, fetchTags])
      const artJson  = artRes  && artRes.ok  ? await artRes.json()  : {}
      const groupJson = groupRes && groupRes.ok ? await groupRes.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 groupItems = Array.isArray(groupJson.data ?? groupJson) ? (groupJson.data ?? groupJson).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)
      setGroups(groupItems)
      setUsers(userItems)
      setTags(tagItems)
      setActiveIdx(-1)
      setOpen(artItems.length > 0 || groupItems.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 === 'group') window.location.href = item.urls?.public ?? item.profile_url ?? `/groups/${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 === 'opening' || phase === 'open' || phase === 'closing') ? 1 : 0
  const collapsedWidth = 'clamp(8.75rem, 8vw + 4rem, 10.5rem)'
  const expandedWidth = 'min(100%, clamp(15rem, 42vw, 28rem))'

  return (
    <>
      <button
        type="button"
        onClick={openMobileOverlay}
        aria-label="Open search"
        className="md:hidden inline-flex items-center justify-center w-10 h-10 rounded-lg text-soft hover:text-white hover:bg-white/5 transition-colors"
      >
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.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>

      <SearchOverlay
        phase={mobileOverlayPhase}
        query={query}
        inputRef={mobileInputRef}
        loading={loading}
        artworks={artworks}
        groups={groups}
        users={users}
        tags={tags}
        activeIdx={activeIdx}
        onQueryChange={(next) => { setQuery(next); setActiveIdx(-1) }}
        onClose={closeMobileOverlay}
        onSubmit={handleSubmit}
        onKeyDown={handleKeyDown}
        onNavigate={navigate}
      />

      <div
        className="hidden md:block"
        ref={wrapperRef}
        style={{
          position:   'relative',
          height:     '40px',
          width:      isExpanded ? expandedWidth : collapsedWidth,
          maxWidth:   '100%',
          minWidth:   '0',
          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="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</span>
        <kbd className="hidden lg:inline-flex shrink-0 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 160ms ease' }}
      >
        <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"
            role="combobox"
            value={query}
            onChange={e => { setQuery(e.target.value); setActiveIdx(-1) }}
            onFocus={() => hasSuggestions && setOpen(true)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            aria-label="Search"
            aria-autocomplete="list"
            aria-haspopup="listbox"
            aria-expanded={open && hasSuggestions}
            aria-controls={suggestionListId}
            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-11 lg: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="hidden lg:inline-flex 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 && hasSuggestions && (
        <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>
              ))}
            </>
          )}

          {groups.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'}`}>Groups</li>
              {groups.map((group, j) => {
                const flatIdx = artworks.length + j
                return (
                  <li key={group.slug ?? group.id ?? j} role="option" id={`sb-item-${flatIdx}`} aria-selected={activeIdx === flatIdx}>
                    <button type="button" onClick={() => navigate({ type: 'group', ...group })}
                      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]'}`}>
                      {group.avatar_url ? (
                        <img src={group.avatar_url} alt="" aria-hidden="true" className="w-9 h-9 rounded-2xl object-cover shrink-0 bg-white/[0.04] border border-white/[0.08]" loading="lazy" />
                      ) : (
                        <span className="w-9 h-9 rounded-2xl bg-white/[0.04] border border-white/[0.07] inline-flex items-center justify-center shrink-0">
                          <i className="fa-solid fa-people-group text-white/40" />
                        </span>
                      )}
                      <div className="min-w-0">
                        <div className="text-sm font-medium text-white truncate">{group.name}</div>
                        <div className="text-xs text-neutral-400 truncate">{group.headline || `${Number(group.counts?.followers || group.followers_count || 0).toLocaleString()} followers`}</div>
                      </div>
                    </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 || groups.length > 0 ? 'pt-2 border-t border-white/[0.06]' : 'pt-2.5'}`}>Creators</li>
              {users.map((user, j) => {
                const flatIdx = artworks.length + groups.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 || groups.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 + groups.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>
    </>
  )
}
