import { useRef, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { SearchResult, SearchResultType } from '../hooks/useGlobalSearch'
import { sendEvent } from '../analytics'

const TYPE_LABEL: Record<SearchResultType, string> = {
  episode: 'Episode',
  question: 'Q&A',
  resource: 'Download',
  series: 'Series',
}

const TYPE_ICON: Record<SearchResultType, string> = {
  episode: '🎙',
  question: '❓',
  resource: '📄',
  series: '📚',
}

interface Props {
  query: string
  setQuery: (q: string) => void
  results: SearchResult[]
}

export function GlobalSearch({ query, setQuery, results }: Props) {
  const [open, setOpen] = useState(false)
  const [activeIdx, setActiveIdx] = useState(-1)
  const inputRef = useRef<HTMLInputElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const navigate = useNavigate()

  const showDropdown = open && (results.length > 0 || query.trim().length >= 2)

  // Reset active index when results change
  useEffect(() => { setActiveIdx(-1) }, [results])

  // Close on outside click
  useEffect(() => {
    if (!showDropdown) return
    function handleClick(e: MouseEvent) {
      if (
        !inputRef.current?.contains(e.target as Node) &&
        !dropdownRef.current?.contains(e.target as Node)
      ) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [showDropdown])

  function handleSelect(result: SearchResult) {
    setOpen(false)
    const q = query.trim()
    if (q) sendEvent('search_query', { query: q })
    setQuery('')
    if (result.href.startsWith('http')) {
      window.open(result.href, '_blank', 'noreferrer')
    } else {
      navigate(result.href)
    }
  }

  function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (!showDropdown) return
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      setActiveIdx(i => Math.min(i + 1, results.length - 1))
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      setActiveIdx(i => Math.max(i - 1, 0))
    } else if (e.key === 'Enter' && activeIdx >= 0) {
      e.preventDefault()
      handleSelect(results[activeIdx])
    } else if (e.key === 'Escape') {
      setOpen(false)
      inputRef.current?.blur()
    }
  }

  return (
    <div className="global-search" role="search">
      <div className="global-search-input-wrap">
        <span className="global-search-icon" aria-hidden="true">
          <svg width="15" height="15" viewBox="0 0 15 15" fill="none">
            <circle cx="6.5" cy="6.5" r="5" stroke="currentColor" strokeWidth="1.5" />
            <path d="M10.5 10.5L14 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </span>
        <input
          ref={inputRef}
          type="search"
          className="global-search-input"
          placeholder="Search episodes, Q&A, resources…"
          value={query}
          autoComplete="off"
          aria-label="Search site"
          aria-expanded={showDropdown}
          aria-autocomplete="list"
          onChange={e => { setQuery(e.target.value); setOpen(true) }}
          onFocus={() => setOpen(true)}
          onKeyDown={handleKeyDown}
        />
        {query && (
          <button
            type="button"
            className="global-search-clear"
            aria-label="Clear search"
            onClick={() => { setQuery(''); setOpen(false); inputRef.current?.focus() }}
          >×</button>
        )}
      </div>

      {showDropdown && (
        <div
          ref={dropdownRef}
          className="global-search-dropdown"
          role="listbox"
          aria-label="Search results"
        >
          {results.length === 0 ? (
            <p className="global-search-empty">No results for "{query}"</p>
          ) : results.map((result, idx) => (
            <button
              key={result.id}
              type="button"
              role="option"
              aria-selected={idx === activeIdx}
              className={`global-search-result${idx === activeIdx ? ' global-search-result--active' : ''}`}
              onClick={() => handleSelect(result)}
              onMouseEnter={() => setActiveIdx(idx)}
            >
              <span className="global-search-result-icon" aria-hidden="true">
                {TYPE_ICON[result.type]}
              </span>
              <span className="global-search-result-body">
                <span className="global-search-result-title">{result.title}</span>
                <span className="global-search-result-meta">
                  <span className="global-search-result-type">{TYPE_LABEL[result.type]}</span>
                  {result.subtitle && result.subtitle !== TYPE_LABEL[result.type] && (
                    <span className="global-search-result-sub"> · {result.subtitle}</span>
                  )}
                </span>
                {result.scriptSnippet && (
                  <span className="global-search-result-snippet">{result.scriptSnippet}</span>
                )}
              </span>
            </button>
          ))}
          {results.length > 0 && (
            <p className="global-search-hint">↑↓ navigate · Enter select · Esc close</p>
          )}
        </div>
      )}
    </div>
  )
}
