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

interface ConnectionIndicatorProps {
  sourceNodeId?: string;
  targetNodeId?: string;
  isConnecting: boolean;
}

export const ConnectionIndicator: React.FC<ConnectionIndicatorProps> = ({
  sourceNodeId,
  targetNodeId,
  isConnecting
}) => {
  const { nodes } = useCanvasStore();
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    if (isConnecting) {
      const handleMouseMove = (e: MouseEvent) => {
        setMousePosition({ x: e.clientX, y: e.clientY });
      };

      document.addEventListener('mousemove', handleMouseMove);
      return () => document.removeEventListener('mousemove', handleMouseMove);
    }
  }, [isConnecting]);

  if (!isConnecting || !sourceNodeId) return null;

  const sourceNode = nodes.find(n => n.id === sourceNodeId);
  if (!sourceNode) return null;

  return (
    <div className="fixed inset-0 pointer-events-none z-40">
      {/* 连接线 */}
      <svg className="absolute inset-0 w-full h-full">
        <defs>
          <marker
            id="arrowhead"
            markerWidth="10"
            markerHeight="7"
            refX="9"
            refY="3.5"
            orient="auto"
          >
            <polygon
              points="0 0, 10 3.5, 0 7"
              fill="#3b82f6"
            />
          </marker>
        </defs>
        <path
          d={`M ${sourceNode.position.x + 200} ${sourceNode.position.y + 50} Q ${
            (sourceNode.position.x + 200 + mousePosition.x) / 2
          } ${sourceNode.position.y + 50} ${mousePosition.x} ${mousePosition.y}`}
          stroke="#3b82f6"
          strokeWidth="2"
          fill="none"
          strokeDasharray="5,5"
          markerEnd="url(#arrowhead)"
          className="animate-pulse"
        />
      </svg>

      {/* 连接提示 */}
      <div
        className="absolute bg-blue-600 text-white text-xs px-2 py-1 rounded shadow-lg"
        style={{
          left: mousePosition.x + 10,
          top: mousePosition.y - 30
        }}
      >
        拖拽到目标节点的输入端口
      </div>
    </div>
  );
};

// 端口高亮组件
export const PortHighlight: React.FC<{
  nodeId: string;
  portId: string;
  type: 'source' | 'target';
  isCompatible: boolean;
}> = ({ nodeId, portId, type, isCompatible }) => {
  return (
    <div
      className={`absolute w-4 h-4 rounded-full border-2 pointer-events-none z-30 ${
        isCompatible
          ? 'border-green-400 bg-green-100 animate-pulse'
          : 'border-red-400 bg-red-100'
      }`}
      style={{
        transform: 'translate(-50%, -50%)'
      }}
    />
  );
};

// 连接验证提示
export const ConnectionValidationTooltip: React.FC<{
  position: { x: number; y: number };
  message: string;
  type: 'success' | 'error' | 'warning';
}> = ({ position, message, type }) => {
  const getColors = () => {
    switch (type) {
      case 'success':
        return 'bg-green-600 text-white';
      case 'error':
        return 'bg-red-600 text-white';
      case 'warning':
        return 'bg-yellow-600 text-white';
    }
  };

  return (
    <div
      className={`fixed z-50 px-3 py-2 rounded-lg shadow-lg text-sm max-w-xs ${getColors()}`}
      style={{
        left: position.x + 10,
        top: position.y - 40
      }}
    >
      {message}
      <div
        className={`absolute top-full left-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent ${
          type === 'success' ? 'border-t-green-600' :
          type === 'error' ? 'border-t-red-600' :
          'border-t-yellow-600'
        }`}
      />
    </div>
  );
};

// 节点操作提示
export const NodeActionHint: React.FC<{
  nodeId: string;
  action: string;
  description: string;
}> = ({ nodeId, action, description }) => {
  const { nodes } = useCanvasStore();
  const node = nodes.find(n => n.id === nodeId);

  if (!node) return null;

  return (
    <div
      className="absolute bg-gray-800 text-white text-xs px-2 py-1 rounded shadow-lg z-40 pointer-events-none"
      style={{
        left: node.position.x + 100,
        top: node.position.y - 30
      }}
    >
      <div className="font-medium">{action}</div>
      <div className="text-gray-300">{description}</div>
    </div>
  );
};

// 处理进度指示器
export const ProcessingIndicator: React.FC<{
  nodeId: string;
  progress: number;
  status: string;
}> = ({ nodeId, progress, status }) => {
  const { nodes } = useCanvasStore();
  const node = nodes.find(n => n.id === nodeId);

  if (!node || status !== 'loading') return null;

  return (
    <div
      className="absolute bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-40 pointer-events-none"
      style={{
        left: node.position.x + 220,
        top: node.position.y + 20
      }}
    >
      <div className="flex items-center space-x-2">
        <div className="w-3 h-3 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
        <div className="text-xs text-gray-600">
          处理中... {Math.round(progress)}%
        </div>
      </div>
      <div className="w-24 h-1 bg-gray-200 rounded-full mt-1">
        <div
          className="h-1 bg-blue-500 rounded-full transition-all duration-300"
          style={{ width: `${progress}%` }}
        />
      </div>
    </div>
  );
};

// 批量处理状态指示器
export const BatchProcessingIndicator: React.FC<{
  nodeId: string;
  completed: number;
  total: number;
  failed: number;
}> = ({ nodeId, completed, total, failed }) => {
  const { nodes } = useCanvasStore();
  const node = nodes.find(n => n.id === nodeId);

  if (!node || total === 0) return null;

  const progress = (completed / total) * 100;

  return (
    <div
      className="absolute bg-white rounded-lg shadow-lg border border-gray-200 p-3 z-40 pointer-events-none min-w-32"
      style={{
        left: node.position.x + 220,
        top: node.position.y + 20
      }}
    >
      <div className="text-xs font-medium text-gray-800 mb-1">
        批量处理进度
      </div>
      
      <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
        <span>已完成: {completed}/{total}</span>
        {failed > 0 && <span className="text-red-600">失败: {failed}</span>}
      </div>
      
      <div className="w-32 h-2 bg-gray-200 rounded-full">
        <div
          className="h-2 bg-blue-500 rounded-full transition-all duration-300"
          style={{ width: `${progress}%` }}
        />
      </div>
      
      <div className="text-xs text-gray-500 mt-1 text-center">
        {Math.round(progress)}%
      </div>
    </div>
  );
};

// 键盘快捷键提示
export const KeyboardShortcutsHint: React.FC<{
  visible: boolean;
}> = ({ visible }) => {
  if (!visible) return null;

  const shortcuts = [
    { key: '双击空白', action: '创建节点' },
    { key: '单击空白', action: '关闭弹框' },
    { key: 'Delete/Backspace', action: '删除选中节点' },
    { key: '悬停节点', action: '显示删除按钮' },
    { key: 'F1', action: '显示/隐藏快捷键' },
    { key: 'Esc', action: '关闭弹框' },
    { key: 'Space+拖拽', action: '平移画布' },
    { key: '滚轮', action: '缩放画布' }
  ];

  return (
    <div className="fixed bottom-4 left-4 bg-white rounded-lg shadow-lg border border-gray-200 p-4 z-40 max-w-xs">
      <h3 className="text-sm font-medium text-gray-800 mb-2">快捷键</h3>
      <div className="space-y-1">
        {shortcuts.map((shortcut, index) => (
          <div key={index} className="flex justify-between text-xs">
            <span className="text-gray-600">{shortcut.action}</span>
            <kbd className="bg-gray-100 px-1 rounded text-gray-800 font-mono">
              {shortcut.key}
            </kbd>
          </div>
        ))}
      </div>
    </div>
  );
};
