import React, { useCallback, useEffect, useState } from 'react';
import { Menu, Tabs } from '@arco-design/web-react';
import { localNodeData } from '@/pages/flowEditor/sideBar/config/localNodeData';
import { useSelector } from 'react-redux';

const TabPane = Tabs.TabPane;

interface AddNodeMenuProps {
  onAddNode: (nodeType: string, node: any) => void;
  position?: { x: number; y: number }; // 用于画布上下文菜单
  edgeId?: string; // 用于边上下文菜单
}

const AddNodeMenu: React.FC<AddNodeMenuProps> = ({
                                                   onAddNode
                                                 }) => {
  const { projectComponentData, info } = useSelector((state: any) => state.ideContainer);
  const [groupedNodes, setGroupedNodes] = useState<Record<string, any[]>>({});
  const [activeTab, setActiveTab] = useState('common');

  // 按分组组织节点数据
  const formattedNodes = useCallback(() => {
    // 先复制本地节点数据
    const initialGroupedNodes = localNodeData.reduce((acc, node) => {
      if (!acc[node.nodeGroup]) {
        acc[node.nodeGroup] = [];
      }
      acc[node.nodeGroup].push(node);
      return acc;
    }, {} as Record<string, typeof localNodeData>);

    const projectComponent = projectComponentData[info.id];
    if (projectComponent) {
      const projectComp = projectComponent.projectCompDto;
      const projectFlow = projectComponent.projectFlowDto;

      const projectCompList = projectComp && Object.values(projectComp).flat(2) || [];
      const projectFlowList = projectFlow && Object.values(projectFlow).flat(2) || [];

      initialGroupedNodes['application'] = projectCompList.map((v: any) => {
        return {
          ...v,
          nodeName: v.name,
          nodeType: 'BASIC',
          nodeGroup: 'application',
          data: {
            parameters: {
              apiIns: v.def?.apis || [],
              apiOuts: Array.isArray(v.def?.apiOut) ? v.def?.apiOut : (v.def?.apiOut ? [v.def?.apiOut] : []),
              dataIns: v.def?.dataIns || [],
              dataOuts: v.def?.dataOuts || []
            }
          }
        };
      });
      // groupedNodes['composite'] = projectFlowList.map((v: any) => {
      //   return {
      //     ...v,
      //     nodeName: v.name,
      //     nodeType: 'BASE',
      //     nodeGroup: 'application',
      //     data: {
      //       parameters: {
      //         apiIns: v.def.apis,
      //         apiOuts: v.def.apiOut,
      //         dataIns: v.def.dataIns,
      //         dataOuts: v.def.dataOuts
      //       }
      //     }
      //   };
      // });
    }

    // 更新状态以触发重新渲染
    setGroupedNodes(initialGroupedNodes);
  }, [projectComponentData, info.id]);

  const handleAddNode = (nodeType: string, node: any) => {
    onAddNode(nodeType, node);
  };

  // 分组名称映射
  const groupNames: Record<string, string> = {
    'application': '基础组件',
    'composite': '复合组件',
    'common': '系统组件'
  };

  useEffect(() => {
    formattedNodes();
  }, [formattedNodes]);

  const handleTabChange = (key: string) => {
    setActiveTab(key);
  };

  return (
    <div
      style={{
        backgroundColor: '#ffffff',
        padding: '10px',
        borderRadius: '10px',
        maxHeight: '400px',
        display: 'flex',
        flexDirection: 'column'
      }}
    >
      <Tabs defaultActiveTab="common" style={{ flex: '0 0 auto' }} onChange={handleTabChange}>
        {Object.entries(groupedNodes).map(([group, nodes]) => (
          <TabPane key={group} title={groupNames[group] || group}>
            {/* 只有在当前 tab 激活时才渲染内容 */}
            {activeTab === group && (
              <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                <Menu
                  style={{
                    width: 200,
                    border: '1px solid #e4e7ed',
                    borderRadius: 4,
                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)'
                  }}
                  mode="vertical"
                  hasCollapseButton={false}
                >
                  {nodes && nodes.map((node) => (
                    <Menu.Item
                      key={node.nodeType + (node.id || '')}
                      onClick={() => handleAddNode(node.nodeType, node)}
                      style={{
                        padding: '0 16px',
                        height: 36,
                        lineHeight: '36px'
                      }}
                    >
                      {node.nodeName}
                    </Menu.Item>
                  ))}
                </Menu>
              </div>
            )}
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
};

export default AddNodeMenu;