import React, { useState, useEffect, useRef } from 'react';
import { Node } from '@xyflow/react';
import { Drawer, ResizeBox } from '@arco-design/web-react';
import { getNodeEditorByType } from '@/components/FlowEditor/nodeEditors';

interface NodeData {
  type?: string;
  title?: string;
  parameters?: any;
  component?: any;

  [key: string]: any;
}

interface NodeEditModalProps {
  popupContainer: any;
  node: Node<NodeData>;
  isOpen: boolean;
  isDelete: boolean;
  onSave: (data: any) => void;
  onClose: () => void;
}

const NodeEditModal: React.FC<NodeEditModalProps> = ({
                                                       popupContainer,
                                                       node,
                                                       isOpen,
                                                       isDelete,
                                                       onSave,
                                                       onClose
                                                     }) => {
  const [nodeData, setNodeData] = useState<NodeData>({});
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (node) {
      setNodeData(node.data || {});
    }
  }, [node]);

  useEffect(() => {
    setVisible(isOpen);
  }, [isOpen]);

  if (!isOpen || !node) return null;

  const handleSave = () => {
    setVisible(false);
    onSave(nodeData);
  };

  const handleClose = () => {
    setVisible(false);
    onClose();
  };
  // 更新节点数据的通用函数
  const updateNodeData = (key: string, value: any) => {
    setNodeData(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // 获取节点编辑器组件
  const getNodeEditor = () => {
    const nodeType = node?.type || 'basic';
    // 检查是否为本地节点（通过nodeTypeMap中不存在的类型来判断）
    const isLocalNode = nodeType && !['start', 'end', 'basic'].includes(nodeType.toLowerCase());

    const EditorComponent = getNodeEditorByType(
      nodeType.toLowerCase(),
      isLocalNode ? nodeType : undefined
    );

    return (
      <EditorComponent
        node={node}
        nodeData={nodeData}
        updateNodeData={updateNodeData}
      />
    );
  };

  return (
    <Drawer
      style={{
        boxShadow: '0 5px 15px rgba(0, 0, 0, 0.2)',
        minWidth: 300,
        width: 'max-content',
        maxWidth: '80vw',
        height: '95%',
        bottom: 0,
        borderRadius: 10
      }}
      title={`编辑节点: ${nodeData.title || node?.type || '未知类型'}`}
      visible={visible}
      placement="left"
      mask={false}
      maskClosable={false}
      footer={null}
      getPopupContainer={() => popupContainer?.current || document.body}
      onOk={handleSave}
      onCancel={isDelete ? handleClose : handleSave}
    >
      {getNodeEditor()}
    </Drawer>
  );
};

export default NodeEditModal;