'use client'

import { useState, useEffect, useRef } from 'react'

interface CommandItem {
  id: string
  label: string
  group: string
  onSelect: () => void
}

export interface CommandPaletteProps {
  open: boolean
  onClose: () => void
  items: CommandItem[]
}

export function CommandPalette({ open, onClose, items }: CommandPaletteProps) {
  const [query, setQuery] = useState('')
  const [activeIndex, setActiveIndex] = useState(0)
  const inputRef = useRef<HTMLInputElement>(null)

  const filtered = items.filter((item) => item.label.toLowerCase().includes(query.toLowerCase()))

  const groups = Array.from(new Set(filtered.map((i) => i.group)))

  useEffect(() => {
    if (open) {
      setQuery('')
      setActiveIndex(0)
      requestAnimationFrame(() => inputRef.current?.focus())
    }
  }, [open])

  useEffect(() => {
    if (!open) return

    function handleKey(e: KeyboardEvent) {
      if (e.key === 'Escape') {
        onClose()
        return
      }
      if (e.key === 'ArrowDown') {
        e.preventDefault()
        setActiveIndex((i) => Math.min(i + 1, filtered.length - 1))
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault()
        setActiveIndex((i) => Math.max(i - 1, 0))
      }
      if (e.key === 'Enter' && filtered[activeIndex]) {
        filtered[activeIndex].onSelect()
        onClose()
      }
    }

    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [open, onClose, filtered, activeIndex])

  if (!open) return null

  let flatIndex = -1

  return (
    <div className="fixed inset-0 z-[70] flex items-start justify-center pt-[20vh]">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} role="presentation" />
      <div className="relative z-10 w-full max-w-lg overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--popover)] shadow-2xl">
        <div className="flex items-center border-b border-[var(--border)] px-4">
          <svg
            className="mr-2 h-4 w-4 text-[var(--muted-foreground)]"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => {
              setQuery(e.target.value)
              setActiveIndex(0)
            }}
            placeholder="Type a command or search..."
            className="flex-1 bg-transparent py-3 text-sm outline-none"
          />
        </div>

        <div className="max-h-72 overflow-y-auto py-2">
          {groups.map((group) => (
            <div key={group}>
              <div className="px-4 py-1.5 text-xs font-medium text-[var(--muted-foreground)]">
                {group}
              </div>
              {filtered
                .filter((i) => i.group === group)
                .map((item) => {
                  flatIndex++
                  const idx = flatIndex
                  return (
                    <button
                      key={item.id}
                      onClick={() => {
                        item.onSelect()
                        onClose()
                      }}
                      className={`flex w-full px-4 py-2 text-sm ${
                        idx === activeIndex ? 'bg-[var(--accent)]' : ''
                      }`}
                    >
                      {item.label}
                    </button>
                  )
                })}
            </div>
          ))}
          {filtered.length === 0 && (
            <p className="px-4 py-6 text-center text-sm text-[var(--muted-foreground)]">
              No results found.
            </p>
          )}
        </div>
      </div>
    </div>
  )
}
