import React, { useState, useEffect } from 'react';
import { Node } from '@xyflow/react';
import { Modal, Input, Form, Select } from '@arco-design/web-react';

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

  [key: string]: any;
}

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

const NodeEditModal: React.FC<NodeEditModalProps> = ({
                                                       node,
                                                       isOpen,
                                                       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 renderContent = () => {
    const nodeType = node?.type || 'basic';

    switch (nodeType) {
      case 'start':
      case 'end':
      case 'basic':
      default:
        return (
          <Form layout="vertical">
            <Form.Item label="节点标题">
              <Input
                value={nodeData.title || ''}
                onChange={(value) => updateNodeData('title', value)}
              />
            </Form.Item>
            <Form.Item label="描述">
              <Input.TextArea
                value={nodeData.description || ''}
                onChange={(value) => updateNodeData('description', value)}
              />
            </Form.Item>
            <Form.Item label="节点类型">
              <Select
                value={nodeData.category || ''}
                onChange={(value) => updateNodeData('category', value)}
                options={[
                  { label: '数据处理', value: 'data' },
                  { label: '逻辑判断', value: 'logic' },
                  { label: '外部接口', value: 'api' }
                ]}
              />
            </Form.Item>
          </Form>
        );
    }
  };

  return (
    <Modal
      title={`编辑节点: ${nodeData.title || node?.type || '未知类型'}`}
      visible={visible}
      onOk={handleSave}
      onCancel={handleClose}
      autoFocus={false}
      focusLock={true}
    >
      {renderContent()}
    </Modal>
  );
};

export default NodeEditModal;