import React, { useCallback } from 'react';
import { Menu } from '@arco-design/web-react';
import AddNodeMenu from './addNodeMenu';

const SubMenu = Menu.SubMenu;

interface PaneContextMenuProps {
  onAddNode: (nodeType: string, position: { x: number; y: number }, node: any) => void;
  position: { x: number; y: number };
}

const PaneContextMenu: React.FC<PaneContextMenuProps> = ({
                                                           onAddNode,
                                                           position
                                                         }) => {
  // 包装onAddNode函数以适配AddNodeMenu组件的接口
  const handleAddNode = useCallback((nodeType: string, node: any) => {
    onAddNode(nodeType, position, node);
  }, [onAddNode, position]);

  // 处理粘贴节点
  const handlePasteNode = useCallback(() => {
    // 创建自定义粘贴事件
    const pasteEvent = new ClipboardEvent('paste', {
      clipboardData: new DataTransfer()
    });
    pasteEvent.clipboardData?.setData('text', 'paste-node');
    document.dispatchEvent(pasteEvent);
  }, []);

  // 检查是否有复制的节点数据
  const hasCopiedNode = !!localStorage.getItem('copiedNode');

  return (
    <Menu
      style={{
        minWidth: 200,
        border: '1px solid #e4e7ed',
        borderRadius: 4,
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)'
      }}
      triggerProps={{ trigger: 'click' }}
    >
      <SubMenu
        key="add-node"
        title="添加节点"
        popup
        triggerProps={{
          popupStyle: { height: 'auto', maxHeight: 'none' }
        }}
      >
        <AddNodeMenu onAddNode={(nodeType, node) => {
          handleAddNode(nodeType, node);
        }} />
      </SubMenu>
      {hasCopiedNode && (
        <Menu.Item key="paste" onClick={handlePasteNode}>
          粘贴节点
        </Menu.Item>
      )}
    </Menu>
  );
};

export default PaneContextMenu;