import React, { useEffect, useState, useRef } from 'react';
import { NodeType } from '../../types/canvas';
import { useCanvasStore } from '../../store/canvasStore';

interface NodeSelectorProps {
  position: { x: number; y: number };
  onSelect: (nodeType: NodeType, position: { x: number; y: number }) => void;
  onClose: () => void;
}

interface CalculatedPosition {
  x: number;
  y: number;
  placement: 'top' | 'bottom' | 'left' | 'right';
}

export const NodeSelector: React.FC<NodeSelectorProps> = ({ position, onSelect, onClose }) => {
  const [calculatedPosition, setCalculatedPosition] = useState<CalculatedPosition>({
    x: position.x,
    y: position.y,
    placement: 'bottom'
  });
  const [searchTerm, setSearchTerm] = useState('');
  const selectorRef = useRef<HTMLDivElement>(null);
  // 计算最佳位置
  const calculateOptimalPosition = (): CalculatedPosition => {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    // 弹框的预估尺寸
    const modalWidth = 320; // max-w-md 约等于 320px
    const modalHeight = 480; // 预估高度
    const padding = 20; // 边距

    let x = position.x;
    let y = position.y;
    let placement: 'top' | 'bottom' | 'left' | 'right' = 'bottom';

    // 检查右侧空间
    if (x + modalWidth + padding > viewportWidth) {
      x = position.x - modalWidth;
      placement = 'left';
    }

    // 检查下方空间
    if (y + modalHeight + padding > viewportHeight) {
      y = position.y - modalHeight;
      placement = placement === 'left' ? 'left' : 'top';
    }

    // 确保不超出左边界
    if (x < padding) {
      x = padding;
    }

    // 确保不超出上边界
    if (y < padding) {
      y = padding;
    }

    return { x, y, placement };
  };

  // 组件挂载后计算位置
  useEffect(() => {
    const newPosition = calculateOptimalPosition();
    setCalculatedPosition(newPosition);
  }, [position]);

  // 点击外部关闭和键盘导航
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (selectorRef.current && !selectorRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [onClose]);

  const nodeCategories = {
    '输入节点': [
      { type: 'textInput' as NodeType, label: '文本输入', icon: '📝', description: '输入文本内容' },
      { type: 'imageUpload' as NodeType, label: '图片上传', icon: '🖼️', description: '上传单张图片' },
      { type: 'folderUpload' as NodeType, label: '文件夹', icon: '📁', description: '批量上传图片' }
    ],
    '处理节点': [
      { type: 'promptOptimize' as NodeType, label: '提示词优化', icon: '✨', description: 'AI优化提示词' },
      { type: 'imageGenerate' as NodeType, label: '图片生成', icon: '🎨', description: '根据提示词生成图片' },
      { type: 'imageEdit' as NodeType, label: '图片编辑', icon: '✏️', description: '编辑和修改图片' },
      { type: 'videoGenerate' as NodeType, label: '视频生成', icon: '🎬', description: '图片转动态视频' }
    ],
    '输出节点': [
      { type: 'textDisplay' as NodeType, label: '文本显示', icon: '📄', description: '显示文本结果' },
      { type: 'imageDisplay' as NodeType, label: '图片显示', icon: '🖼️', description: '显示图片结果' },
      { type: 'videoPlayer' as NodeType, label: '视频播放', icon: '▶️', description: '播放视频结果' },
      { type: 'batchGrid' as NodeType, label: '批量结果', icon: '📊', description: '网格显示批量结果' }
    ]
  };

  return (
    <div
      ref={selectorRef}
      className={`fixed bg-white rounded-lg shadow-xl border border-gray-200 p-4 z-50 max-w-md transition-all duration-200 ${
        calculatedPosition.placement === 'top' ? 'animate-slide-up' :
        calculatedPosition.placement === 'bottom' ? 'animate-slide-down' :
        calculatedPosition.placement === 'left' ? 'animate-slide-left' :
        'animate-slide-right'
      }`}
      style={{
        left: calculatedPosition.x,
        top: calculatedPosition.y,
        maxHeight: '80vh',
        overflowY: 'auto'
      }}
    >
      {/* 位置指示器 */}
      {calculatedPosition.placement === 'bottom' && (
        <div className="absolute -top-2 left-6 w-4 h-4 bg-white border-l border-t border-gray-200 transform rotate-45"></div>
      )}
      {calculatedPosition.placement === 'top' && (
        <div className="absolute -bottom-2 left-6 w-4 h-4 bg-white border-r border-b border-gray-200 transform rotate-45"></div>
      )}
      {calculatedPosition.placement === 'right' && (
        <div className="absolute -left-2 top-6 w-4 h-4 bg-white border-l border-b border-gray-200 transform rotate-45"></div>
      )}
      {calculatedPosition.placement === 'left' && (
        <div className="absolute -right-2 top-6 w-4 h-4 bg-white border-r border-t border-gray-200 transform rotate-45"></div>
      )}

      <div className="flex items-center justify-between mb-3">
        <h3 className="text-lg font-semibold text-gray-800">选择节点类型</h3>
        <button
          onClick={onClose}
          className="text-gray-400 hover:text-gray-600 transition-colors p-1 hover:bg-gray-100 rounded"
        >
          ✕
        </button>
      </div>

      {/* 搜索框 */}
      <div className="mb-4">
        <input
          type="text"
          placeholder="搜索节点..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          autoFocus
        />
      </div>

      <div className="space-y-3 max-h-96 overflow-y-auto">
        {Object.entries(nodeCategories).map(([category, nodes]) => {
          // 过滤节点
          const filteredNodes = nodes.filter(node =>
            searchTerm === '' ||
            node.label.toLowerCase().includes(searchTerm.toLowerCase()) ||
            node.description.toLowerCase().includes(searchTerm.toLowerCase())
          );

          if (filteredNodes.length === 0) return null;

          return (
            <div key={category}>
              <h4 className="text-sm font-medium text-gray-600 mb-2 sticky top-0 bg-white">{category}</h4>
              <div className="grid grid-cols-1 gap-1.5">
                {filteredNodes.map(node => (
                  <button
                    key={node.type}
                    className="flex items-center p-2.5 rounded-lg border border-gray-200 hover:border-blue-300 hover:bg-blue-50 transition-all duration-200 text-left group"
                    onClick={() => {
                      onSelect(node.type, position);
                      onClose();
                    }}
                  >
                    <div className="text-xl mr-3 group-hover:scale-110 transition-transform">{node.icon}</div>
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-gray-800 text-sm truncate">{node.label}</div>
                      <div className="text-xs text-gray-500 truncate">{node.description}</div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          );
        })}

        {/* 无搜索结果 */}
        {searchTerm && Object.entries(nodeCategories).every(([_, nodes]) =>
          nodes.every(node =>
            !node.label.toLowerCase().includes(searchTerm.toLowerCase()) &&
            !node.description.toLowerCase().includes(searchTerm.toLowerCase())
          )
        ) && (
          <div className="text-center py-8 text-gray-500">
            <div className="text-4xl mb-2">🔍</div>
            <div className="text-sm">未找到匹配的节点</div>
            <div className="text-xs text-gray-400 mt-1">尝试其他关键词</div>
          </div>
        )}
      </div>
    </div>
  );
};
