import { useState, useEffect, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { Search, Loader2, ArrowRight, FileText, Clock } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { sessionsApi } from '@/api/sessions'
import type { TreeListItem } from '@/types'
import type { Session } from '@/types/session'
import { getTreeNavigatePath } from '@/lib/routing'
import { cn } from '@/lib/utils'

interface CommandPaletteProps {
  open: boolean
  onClose: () => void
}

interface ResultItem {
  id: string
  type: 'tree' | 'session'
  title: string
  subtitle?: string
  icon: 'tree' | 'session'
  path: string
}

export function CommandPalette({ open, onClose }: CommandPaletteProps) {
  const navigate = useNavigate()
  const inputRef = useRef<HTMLInputElement>(null)
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<ResultItem[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [selectedIndex, setSelectedIndex] = useState(0)
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  // Focus input when opened
  useEffect(() => {
    if (open) {
      setQuery('')
      setResults([])
      setSelectedIndex(0)
      // Slight delay to ensure modal is rendered
      setTimeout(() => inputRef.current?.focus(), 50)
    }
  }, [open])

  // Close on Escape
  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [open, onClose])

  // Debounced search
  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current)
    if (query.length < 2) {
      setResults([])
      setIsSearching(false)
      return
    }
    setIsSearching(true)
    debounceRef.current = setTimeout(async () => {
      try {
        const [trees, sessions] = await Promise.all([
          treesApi.search(query, 6),
          sessionsApi.list({ size: 5 }).catch(() => [] as Session[]),
        ])

        const treeResults: ResultItem[] = trees.map((t: TreeListItem) => ({
          id: t.id,
          type: 'tree' as const,
          title: t.name,
          subtitle: t.description || undefined,
          icon: 'tree' as const,
          path: getTreeNavigatePath(t.id, t.tree_type),
        }))

        // Filter sessions by tree name matching query
        const sessionResults: ResultItem[] = sessions
          .filter((s: Session) =>
            s.tree_snapshot?.name?.toLowerCase().includes(query.toLowerCase())
          )
          .slice(0, 3)
          .map((s: Session) => ({
            id: s.id,
            type: 'session' as const,
            title: s.tree_snapshot?.name || 'Session',
            subtitle: s.completed_at ? 'Completed' : 'In progress',
            icon: 'session' as const,
            path: `/sessions/${s.id}`,
          }))

        setResults([...treeResults, ...sessionResults])
      } catch {
        setResults([])
      } finally {
        setIsSearching(false)
      }
    }, 250)
    return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
  }, [query])

  const handleSelect = useCallback((item: ResultItem) => {
    onClose()
    navigate(item.path)
  }, [navigate, onClose])

  // Keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      setSelectedIndex(i => Math.min(i + 1, results.length - 1))
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      setSelectedIndex(i => Math.max(i - 1, 0))
    } else if (e.key === 'Enter' && results[selectedIndex]) {
      e.preventDefault()
      handleSelect(results[selectedIndex])
    }
  }

  if (!open) return null

  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center pt-[20vh]">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm animate-fade-in"
        onClick={onClose}
      />

      {/* Palette */}
      <div className="relative w-full max-w-lg rounded-xl border border-border bg-card shadow-2xl animate-scale-in">
        {/* Search input */}
        <div className="flex items-center gap-3 border-b border-border px-4 py-3">
          <Search size={18} className="shrink-0 text-muted-foreground" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={e => { setQuery(e.target.value); setSelectedIndex(0) }}
            onKeyDown={handleKeyDown}
            placeholder="Search flows, sessions…"
            className="flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none"
          />
          <kbd className="rounded border border-border bg-background px-1.5 py-0.5 font-label text-[0.625rem] text-muted-foreground">
            ESC
          </kbd>
        </div>

        {/* Results */}
        <div className="max-h-72 overflow-y-auto">
          {isSearching ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
            </div>
          ) : query.length >= 2 && results.length === 0 ? (
            <div className="px-4 py-8 text-center text-sm text-muted-foreground">
              No results for &ldquo;{query}&rdquo;
            </div>
          ) : results.length > 0 ? (
            <div className="p-1">
              {results.map((item, i) => (
                <button
                  key={item.id}
                  onClick={() => handleSelect(item)}
                  onMouseEnter={() => setSelectedIndex(i)}
                  className={cn(
                    'flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors',
                    i === selectedIndex
                      ? 'bg-accent text-foreground'
                      : 'text-muted-foreground hover:bg-accent/50'
                  )}
                >
                  {item.type === 'tree' ? (
                    <FileText size={16} className="shrink-0 opacity-60" />
                  ) : (
                    <Clock size={16} className="shrink-0 opacity-60" />
                  )}
                  <div className="min-w-0 flex-1">
                    <p className="text-sm font-medium truncate">{item.title}</p>
                    {item.subtitle && (
                      <p className="text-[0.6875rem] text-muted-foreground truncate">{item.subtitle}</p>
                    )}
                  </div>
                  {i === selectedIndex && (
                    <ArrowRight size={14} className="shrink-0 opacity-40" />
                  )}
                </button>
              ))}
            </div>
          ) : (
            <div className="px-4 py-6 text-center text-sm text-muted-foreground">
              Type to search flows and sessions
            </div>
          )}
        </div>

        {/* Footer hints */}
        {results.length > 0 && (
          <div className="flex items-center gap-4 border-t border-border px-4 py-2">
            <span className="flex items-center gap-1 text-[0.625rem] text-muted-foreground">
              <kbd className="rounded border border-border bg-background px-1 py-px font-label">↑↓</kbd>
              Navigate
            </span>
            <span className="flex items-center gap-1 text-[0.625rem] text-muted-foreground">
              <kbd className="rounded border border-border bg-background px-1 py-px font-label">↵</kbd>
              Open
            </span>
          </div>
        )}
      </div>
    </div>
  )
}
