import React from 'react'
import { createPortal } from 'react-dom'
import { useActiveCategoriesOnly } from '../../stores/useCategoryStore'

interface CategorySelectorProps {
  isOpen: boolean
  position: { x: number; y: number }
  currentName: string
  onSelect: (categoryName: string) => void
  onCancel: () => void
}

export const CategorySelector: React.FC<CategorySelectorProps> = ({
  isOpen,
  position,
  currentName,
  onSelect,
  onCancel
}) => {
  const activeCategories = useActiveCategoriesOnly()
  const [selectedIndex, setSelectedIndex] = React.useState(-1)
  const dropdownRef = React.useRef<HTMLDivElement>(null)

  // 处理键盘导航
  const handleKeyDown = React.useCallback((e: KeyboardEvent) => {
    if (!isOpen) return

    switch (e.key) {
      case 'Escape':
        e.preventDefault()
        onCancel()
        break
      case 'ArrowDown':
        e.preventDefault()
        setSelectedIndex(prev => 
          prev < activeCategories.length ? prev + 1 : prev
        )
        break
      case 'ArrowUp':
        e.preventDefault()
        setSelectedIndex(prev => prev > -1 ? prev - 1 : prev)
        break
      case 'Enter':
        e.preventDefault()
        if (selectedIndex === -1) {
          onSelect(currentName) // 保持原名称
        } else if (selectedIndex < activeCategories.length) {
          onSelect(activeCategories[selectedIndex].title)
        }
        break
    }
  }, [isOpen, selectedIndex, activeCategories, currentName, onSelect, onCancel])

  // 监听键盘事件
  React.useEffect(() => {
    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown)
      return () => document.removeEventListener('keydown', handleKeyDown)
    }
  }, [isOpen, handleKeyDown])

  // 点击外部关闭
  React.useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        onCancel()
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [isOpen, onCancel])

  // 计算下拉框位置，确保不超出视窗
  const adjustedPosition = React.useMemo(() => {
    const maxHeight = 300 // 下拉框最大高度
    const padding = 10
    
    let { x, y } = position
    
    // 检查是否超出右边界
    if (x + 250 > window.innerWidth) {
      x = window.innerWidth - 250 - padding
    }
    
    // 检查是否超出下边界
    if (y + maxHeight > window.innerHeight) {
      y = position.y - maxHeight - padding
    }
    
    return { x: Math.max(padding, x), y: Math.max(padding, y) }
  }, [position])

  // 自动聚焦
  React.useEffect(() => {
    if (isOpen && dropdownRef.current) {
      dropdownRef.current.focus()
    }
  }, [isOpen])

  // 如果不显示，返回 null
  if (!isOpen) return null

  const dropdown = (
    <div
      ref={dropdownRef}
      className="fixed z-50 bg-white border border-gray-300 rounded-lg shadow-lg min-w-[200px] max-w-[300px] max-h-[300px] overflow-hidden"
      style={{
        left: adjustedPosition.x,
        top: adjustedPosition.y,
      }}
      tabIndex={-1}
    >
      {/* 头部 */}
      <div className="px-3 py-2 bg-gray-50 border-b border-gray-200">
        <div className="text-sm font-medium text-gray-700">选择分类</div>
        <div className="text-xs text-gray-500 truncate">当前: {currentName}</div>
      </div>

      {/* 选项列表 */}
      <div className="max-h-[240px] overflow-y-auto">
        {/* 保持原名称选项 */}
        <div
          className={`px-3 py-2 cursor-pointer transition-colors ${
            selectedIndex === -1
              ? 'bg-blue-50 text-blue-700'
              : 'hover:bg-gray-50'
          }`}
          onClick={() => onSelect(currentName)}
          onMouseEnter={() => setSelectedIndex(-1)}
        >
          <div className="flex items-center">
            <div className="w-3 h-3 rounded-full bg-gray-400 mr-2 flex-shrink-0" />
            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium text-gray-700 truncate">
                保持原名称
              </div>
              <div className="text-xs text-gray-500 truncate">
                {currentName}
              </div>
            </div>
          </div>
        </div>

        {/* 分隔线 */}
        {activeCategories.length > 0 && (
          <div className="border-t border-gray-200 my-1" />
        )}

        {/* 分类选项 */}
        {activeCategories.length === 0 ? (
          <div className="px-3 py-4 text-center text-gray-500 text-sm">
            暂无可用分类
          </div>
        ) : (
          activeCategories.map((category, index) => (
            <div
              key={category.id}
              className={`px-3 py-2 cursor-pointer transition-colors ${
                selectedIndex === index
                  ? 'bg-blue-50 text-blue-700'
                  : 'hover:bg-gray-50'
              }`}
              onClick={() => onSelect(category.title)}
              onMouseEnter={() => setSelectedIndex(index)}
            >
              <div className="flex items-center">
                <div
                  className="w-3 h-3 rounded-full mr-2 flex-shrink-0"
                  style={{ backgroundColor: category.color }}
                />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-gray-900 truncate">
                    {category.title}
                  </div>
                  {category.ai_prompt && (
                    <div className="text-xs text-gray-500 truncate">
                      {category.ai_prompt}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 底部提示 */}
      <div className="px-3 py-2 bg-gray-50 border-t border-gray-200">
        <div className="text-xs text-gray-500">
          ↑↓ 导航 • Enter 选择 • Esc 取消
        </div>
      </div>
    </div>
  )

  // 使用 Portal 渲染到 body
  return createPortal(dropdown, document.body)
}

export default CategorySelector
