import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { Plus, Play, FileText, Bookmark, Users, X } from 'lucide-react'
import { treesApi } from '@/api/trees'
import type { TreeListItem } from '@/types'
import { getTreeNavigatePath } from '@/lib/routing'
import { cn } from '@/lib/utils'

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

interface QuickAction {
  id: string
  icon: typeof Plus
  label: string
  description: string
  path: string
  color: string
}

const ACTIONS: QuickAction[] = [
  { id: 'new-tree', icon: Plus, label: 'New Troubleshooting Flow', description: 'Create a branching decision tree', path: '/trees/new', color: '#3b82f6' },
  { id: 'new-project', icon: Plus, label: 'New Project', description: 'Create a step-by-step project', path: '/flows/new', color: '#8b5cf6' },
  { id: 'sessions', icon: Play, label: 'View Sessions', description: 'See active and recent sessions', path: '/sessions', color: '#f59e0b' },
  { id: 'step-library', icon: Bookmark, label: 'Step Library', description: 'Browse reusable steps', path: '/step-library', color: '#10b981' },
  { id: 'exports', icon: FileText, label: 'Exports & Shares', description: 'View shared session exports', path: '/shares', color: '#6366f1' },
  { id: 'team', icon: Users, label: 'Team Settings', description: 'Manage team members and roles', path: '/account', color: '#ec4899' },
]

export function QuickLaunch({ open, onClose }: QuickLaunchProps) {
  const navigate = useNavigate()
  const [recentTrees, setRecentTrees] = useState<TreeListItem[]>([])
  const [selectedIndex, setSelectedIndex] = useState(0)
  const containerRef = useRef<HTMLDivElement>(null)

  const allItems = [...ACTIONS.map(a => ({ type: 'action' as const, ...a })), ...recentTrees.slice(0, 4).map(t => ({ type: 'tree' as const, ...t }))]
  const totalItems = allItems.length

  useEffect(() => {
    if (open) {
      setSelectedIndex(0)
      treesApi.list({ sort_by: 'updated_at' })
        .then(trees => setRecentTrees(trees.slice(0, 4)))
        .catch(() => {})
    }
  }, [open])

  useEffect(() => {
    if (!open) return
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
      if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedIndex(i => Math.min(i + 1, totalItems - 1)) }
      if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedIndex(i => Math.max(i - 1, 0)) }
      if (e.key === 'Enter') {
        e.preventDefault()
        const item = allItems[selectedIndex]
        if (!item) return
        onClose()
        if (item.type === 'action') navigate(item.path)
        else navigate(getTreeNavigatePath(item.id, item.tree_type))
      }
    }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [open, selectedIndex, totalItems, allItems, navigate, onClose])

  if (!open) return null

  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center pt-[15vh]">
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm animate-fade-in" onClick={onClose} />
      <div ref={containerRef} className="relative w-full max-w-md rounded-xl border border-border bg-card shadow-2xl animate-scale-in">
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <h3 className="text-sm font-heading font-semibold text-foreground">Quick Launch</h3>
          <button onClick={onClose} className="rounded-lg p-1 text-muted-foreground hover:text-foreground">
            <X size={16} />
          </button>
        </div>

        <div className="max-h-80 overflow-y-auto p-1">
          {/* Actions */}
          <p className="px-3 py-1.5 text-[0.625rem] font-bold uppercase tracking-wider text-muted-foreground">Actions</p>
          {ACTIONS.map((action, i) => {
            const Icon = action.icon
            return (
              <button
                key={action.id}
                onClick={() => { onClose(); navigate(action.path) }}
                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'
                )}
              >
                <div
                  className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"
                  style={{ backgroundColor: `${action.color}15` }}
                >
                  <Icon size={16} style={{ color: action.color }} />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-medium">{action.label}</p>
                  <p className="text-[0.6875rem] text-muted-foreground">{action.description}</p>
                </div>
              </button>
            )
          })}

          {/* Recent flows */}
          {recentTrees.length > 0 && (
            <>
              <p className="mt-2 px-3 py-1.5 text-[0.625rem] font-bold uppercase tracking-wider text-muted-foreground">Recent Flows</p>
              {recentTrees.slice(0, 4).map((tree, ti) => {
                const idx = ACTIONS.length + ti
                return (
                  <button
                    key={tree.id}
                    onClick={() => { onClose(); navigate(getTreeNavigatePath(tree.id, tree.tree_type)) }}
                    onMouseEnter={() => setSelectedIndex(idx)}
                    className={cn(
                      'flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors',
                      idx === selectedIndex ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/50'
                    )}
                  >
                    <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-card border border-border text-base">
                      {tree.tree_type === 'procedural' ? '📋' : '🔧'}
                    </div>
                    <div className="min-w-0">
                      <p className="text-sm font-medium truncate">{tree.name}</p>
                      <p className="text-[0.6875rem] text-muted-foreground">
                        {tree.tree_type === 'procedural' ? 'Project' : 'Troubleshooting'} · {tree.usage_count} uses
                      </p>
                    </div>
                    <Play size={14} className="ml-auto shrink-0 opacity-40" />
                  </button>
                )
              })}
            </>
          )}
        </div>

        <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>
  )
}
