'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Search, X, ListTodo, Lightbulb, ClipboardList, Mic, CalendarClock, CornerDownLeft, type LucideIcon } from 'lucide-react'

interface Hit { type: 'reminder' | 'thought' | 'item' | 'list' | 'capture' | 'event'; id: string; title: string; sub: string | null; href: string }

const META: Record<Hit['type'], { label: string; Icon: LucideIcon }> = {
  reminder: { label: 'Reminders', Icon: ListTodo },
  thought: { label: 'Thoughts', Icon: Lightbulb },
  item: { label: 'List items', Icon: ClipboardList },
  list: { label: 'Lists', Icon: ClipboardList },
  capture: { label: 'Captures', Icon: Mic },
  event: { label: 'Events', Icon: CalendarClock },
}

// Global search: press "s" on the dashboard (or tap the button) to open a
// command-palette overlay that searches across everything and jumps to it.
export function GlobalSearch() {
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const [q, setQ] = useState('')
  const [results, setResults] = useState<Hit[]>([])
  const [active, setActive] = useState(0)
  const [loading, setLoading] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)
  const listRef = useRef<HTMLDivElement>(null)

  // "s" opens search — but not while typing in a field or with a modifier
  // (so Cmd/Ctrl+S still saves, and you can type an "s" anywhere).
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (open || e.key !== 's' || e.metaKey || e.ctrlKey || e.altKey) return
      const el = e.target as HTMLElement | null
      if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return
      e.preventDefault()
      setOpen(true)
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open])

  // Debounced query.
  useEffect(() => {
    if (!open) return
    const query = q.trim()
    if (query.length < 2) { setResults([]); setActive(0); return }
    setLoading(true)
    const t = setTimeout(async () => {
      try {
        const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { cache: 'no-store' })
        if (res.ok) { setResults((await res.json()).results || []); setActive(0) }
      } finally { setLoading(false) }
    }, 200)
    return () => clearTimeout(t)
  }, [q, open])

  useEffect(() => { if (open) setTimeout(() => inputRef.current?.focus(), 0) }, [open])
  useEffect(() => { listRef.current?.querySelector(`[data-idx="${active}"]`)?.scrollIntoView({ block: 'nearest' }) }, [active])

  const close = useCallback(() => { setOpen(false); setQ(''); setResults([]); setActive(0) }, [])
  const go = useCallback((h: Hit) => { close(); router.push(h.href) }, [close, router])

  const onInputKey = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') { e.preventDefault(); close() }
    else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(a + 1, results.length - 1)) }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(a - 1, 0)) }
    else if (e.key === 'Enter') { e.preventDefault(); const h = results[active]; if (h) go(h) }
  }

  return (
    <>
      <button onClick={() => setOpen(true)} className="p-2 rounded-lg hover:bg-muted text-muted-foreground" aria-label="Search" title="Search (press s)">
        <Search className="h-4 w-4" />
      </button>
      {open && (
        <div className="fixed inset-0 z-[80] flex items-start justify-center px-4 pt-[12vh] bg-black/50 backdrop-blur-sm" onClick={close}>
          <div className="w-full max-w-md rounded-2xl border border-border bg-card shadow-xl overflow-hidden" onClick={e => e.stopPropagation()}>
            <div className="flex items-center gap-2 px-3 border-b border-border">
              <Search className="h-4 w-4 text-muted-foreground shrink-0" />
              <input
                ref={inputRef}
                value={q}
                onChange={e => setQ(e.target.value)}
                onKeyDown={onInputKey}
                placeholder="Search everything…"
                className="flex-1 bg-transparent h-12 text-base focus:outline-none"
              />
              <button onClick={close} className="text-muted-foreground hover:text-foreground shrink-0" aria-label="Close"><X className="h-4 w-4" /></button>
            </div>

            <div ref={listRef} className="max-h-[60vh] overflow-y-auto py-1">
              {q.trim().length < 2 ? (
                <p className="px-4 py-6 text-sm text-muted-foreground text-center">Search reminders, thoughts, lists, captures, and events.</p>
              ) : loading && results.length === 0 ? (
                <p className="px-4 py-6 text-sm text-muted-foreground text-center">Searching…</p>
              ) : results.length === 0 ? (
                <p className="px-4 py-6 text-sm text-muted-foreground text-center">No matches for &ldquo;{q.trim()}&rdquo;.</p>
              ) : (
                results.map((h, idx) => {
                  const header = idx === 0 || results[idx - 1].type !== h.type
                  const Icon = META[h.type].Icon
                  return (
                    <div key={`${h.type}-${h.id}`}>
                      {header && <div className="px-3 pt-2 pb-1 text-xs font-semibold text-muted-foreground">{META[h.type].label}</div>}
                      <button
                        data-idx={idx}
                        onMouseEnter={() => setActive(idx)}
                        onClick={() => go(h)}
                        className={`w-full flex items-center gap-2.5 px-3 py-2 text-left ${idx === active ? 'bg-muted' : ''}`}
                      >
                        <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
                        <span className="min-w-0 flex-1 truncate text-sm">{h.title}</span>
                        {h.sub && <span className="text-xs text-muted-foreground shrink-0 max-w-28 truncate">{h.sub}</span>}
                      </button>
                    </div>
                  )
                })
              )}
            </div>

            <div className="flex items-center gap-3 px-3 py-2 border-t border-border text-[11px] text-muted-foreground">
              <span className="inline-flex items-center gap-1"><CornerDownLeft className="h-3 w-3" /> open</span>
              <span>↑↓ navigate</span>
              <span>esc close</span>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
