import React, { useState } from 'react';
import { Handle, Position } from 'reactflow';
import { NodePort, ProcessingStatus } from '../../types/canvas';
import { useCanvasStore } from '../../store/canvasStore';
import clsx from 'clsx';

interface BaseNodeProps {
  id: string;
  title: string;
  children: React.ReactNode;
  inputs?: NodePort[];
  outputs?: NodePort[];
  className?: string;
}

export const BaseNode: React.FC<BaseNodeProps> = ({
  id,
  title,
  children,
  inputs = [],
  outputs = [],
  className
}) => {
  const [isHovered, setIsHovered] = useState(false);
  const { processingNodes, deleteNode } = useCanvasStore();
  const processingInfo = processingNodes.get(id);
  const status = processingInfo?.status || 'idle';
  const progress = processingInfo?.progress || 0;

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (confirm('确定要删除这个节点吗？')) {
      deleteNode(id);
    }
  };

  return (
    <div
      className={clsx(
        "bg-white rounded-lg shadow-md border-2 border-gray-200 relative",
        "min-w-48 min-h-32 p-4 transition-all duration-200",
        "hover:shadow-lg hover:border-blue-300",
        {
          "border-blue-400 bg-blue-50": status === 'loading',
          "border-green-400 bg-green-50": status === 'success',
          "border-red-400 bg-red-50": status === 'error'
        },
        className
      )}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* 输入端口 */}
      {inputs.map(port => (
        <Handle
          key={port.id}
          type="target"
          position={Position.Left}
          id={port.id}
          className={clsx(
            "w-3 h-3 border-2 border-white transition-all duration-200",
            "hover:scale-125 hover:shadow-lg",
            {
              "bg-purple-500": port.type === 'text',
              "bg-cyan-500": port.type === 'image',
              "bg-pink-500": port.type === 'video',
              "bg-orange-500 w-4 h-4": port.type === 'batch'
            }
          )}
          style={{ top: `${20 + inputs.indexOf(port) * 30}px` }}
        />
      ))}

      {/* 删除按钮 */}
      {isHovered && status !== 'loading' && (
        <button
          onClick={handleDelete}
          className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full hover:bg-red-600 transition-colors duration-200 flex items-center justify-center text-xs font-bold shadow-lg z-10"
          title="删除节点"
        >
          ×
        </button>
      )}

      {/* 节点内容 */}
      <div className="node-content">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-sm font-semibold text-gray-800">{title}</h3>
          {status === 'loading' && (
            <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
          )}
        </div>

        <div className="node-body">
          {children}
        </div>

        {/* 进度条 */}
        {status === 'loading' && progress !== undefined && (
          <div className="mt-2">
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div 
                className="bg-blue-500 h-2 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>
        )}

        {/* 错误信息 */}
        {status === 'error' && processingInfo?.error && (
          <div className="mt-2 text-xs text-red-600 bg-red-50 p-2 rounded">
            {processingInfo.error}
          </div>
        )}
      </div>

      {/* 输出端口 */}
      {outputs.map(port => (
        <Handle
          key={port.id}
          type="source"
          position={Position.Right}
          id={port.id}
          className={clsx(
            "w-3 h-3 border-2 border-white transition-all duration-200",
            "hover:scale-125 hover:shadow-lg",
            {
              "bg-purple-500": port.type === 'text',
              "bg-cyan-500": port.type === 'image',
              "bg-pink-500": port.type === 'video',
              "bg-orange-500 w-4 h-4": port.type === 'batch'
            }
          )}
          style={{ top: `${20 + outputs.indexOf(port) * 30}px` }}
        />
      ))}
    </div>
  );
};
