import React, {useState, useEffect} from 'react';
import {Card, Collapse, Tooltip, message} from 'antd';
import type {NodeDefinition, NodeCategory} from '../types';
import {
    PlayCircleOutlined,
    StopOutlined,
    UserOutlined,
    ApiOutlined,
    CodeOutlined,
    NodeIndexOutlined,
    SplitCellsOutlined,
    AppstoreOutlined,
    BranchesOutlined
} from '@ant-design/icons';
import {getNodeDefinitionList} from "@/pages/Workflow/Definition/Design/service";
import {NodeDefinitionResponse} from "@/pages/Workflow/NodeDesign/types";

const {Panel} = Collapse;

// 图标映射配置
const iconMap: Record<string, any> = {
    'play-circle': PlayCircleOutlined,
    'stop': StopOutlined,
    'user': UserOutlined,
    'api': ApiOutlined,
    'code': CodeOutlined,
    'fork': NodeIndexOutlined,
    'branches': SplitCellsOutlined,
    'apartment': AppstoreOutlined
};

// 节点类型到图标的映射
const typeIconMap: Record<string, any> = {
    'START_EVENT': PlayCircleOutlined,
    'END_EVENT': StopOutlined,
    'USER_TASK': UserOutlined,
    'SERVICE_TASK': ApiOutlined,
    'SCRIPT_TASK': CodeOutlined,
    'EXCLUSIVE_GATEWAY': NodeIndexOutlined,
    'PARALLEL_GATEWAY': SplitCellsOutlined,
    'SUB_PROCESS': AppstoreOutlined,
    'CALL_ACTIVITY': BranchesOutlined
};

// 节点分类配置
const categoryConfig: Record<NodeCategory, {
    label: string;
    key: string;
}> = {
    EVENT: {label: '事件节点', key: '1'},
    TASK: {label: '任务节点', key: '2'},
    GATEWAY: {label: '网关节点', key: '3'},
    CONTAINER: {label: '容器节点', key: '4'},
};

interface NodePanelProps {
    onNodeDragStart?: (node: NodeDefinitionResponse, e: React.DragEvent) => void,
    nodeDefinitions?: NodeDefinitionResponse[]
}

const NodePanel: React.FC<NodePanelProps> = ({onNodeDragStart}) => {
    const [loading, setLoading] = useState(false);
    const [nodeDefinitions, setNodeDefinitions] = useState<NodeDefinitionResponse[]>([]);

    // 加载节点定义列表
    const loadNodeDefinitions = async () => {
        setLoading(true);
        try {
            const data = await getNodeDefinitionList();
            console.log(data)
            setNodeDefinitions(data);
        } catch (error) {
            if (error instanceof Error) {
                message.error(error.message);
            }
        } finally {
            setLoading(false);
        }
    };

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

    // 按分类对节点进行分组
    const groupedNodes = nodeDefinitions.reduce((acc, node) => {
        if (!acc[node.category]) {
            acc[node.category] = [];
        }
        acc[node.category].push(node);
        return acc;
    }, {} as Record<NodeCategory, NodeDefinitionResponse[]>);

    // 处理节点拖拽开始事件
    const handleDragStart = (node: NodeDefinitionResponse, e: React.DragEvent) => {
        e.dataTransfer.setData('node', JSON.stringify(node));
        onNodeDragStart?.(node, e);
    };

    // 渲染节点图标
    const renderNodeIcon = (node: NodeDefinitionResponse) => {
        const iconName = node.uiVariables?.style.icon;
        // 首先尝试使用配置的图标
        let IconComponent = iconMap[iconName];

        // 如果没有找到对应的图标，使用节点类型对应的默认图标
        if (!IconComponent) {
            IconComponent = typeIconMap[node.nodeType] || AppstoreOutlined;
        }

        return (
            <IconComponent
                style={{
                    color: node.uiVariables?.style.iconColor || '#1890ff',
                    fontSize: '16px',
                    marginRight: '6px'
                }}
            />
        );
    };

    const getNodeItemStyle = (node: NodeDefinitionResponse) => ({
        width: '100%',
        padding: '10px 12px',
        border: `1px solid ${node.uiVariables?.style.stroke}`,
        borderRadius: '6px',
        cursor: 'move',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: '10px',
        background: node.uiVariables?.style.fill,
        transition: 'all 0.3s',
        boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
        '&:hover': {
            transform: 'translateY(-1px)',
            boxShadow: '0 3px 6px rgba(0,0,0,0.1)',
        }
    });

    const tooltipStyle = {
        maxWidth: '300px'
    };

    const tooltipOverlayInnerStyle = {
        padding: '12px 16px'
    };

    // 构建折叠面板的 items，只包含有节点的分类
    const collapseItems = Object.entries(categoryConfig)
        .filter(([category]) => groupedNodes[category as NodeCategory]?.length > 0) // 过滤掉没有节点的分类
        .map(([category, {label, key}]) => ({
            key,
            label: <span style={{fontSize: '14px', fontWeight: 500}}>{label}</span>,
            children: (
                <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '12px',
                    padding: '8px 4px'
                }}>
                    {groupedNodes[category as NodeCategory]?.map(node => (
                        <Tooltip
                            key={node.id}
                            title={
                                <div>
                                    <div style={{fontSize: '14px', fontWeight: 500}}>{node.description}</div>
                                </div>
                            }
                            overlayStyle={tooltipStyle}
                            overlayInnerStyle={tooltipOverlayInnerStyle}
                            placement="right"
                            arrow={false}
                        >
                            <div
                                draggable
                                onDragStart={(e) => handleDragStart(node, e)}
                                style={getNodeItemStyle(node)}
                            >
                                <div style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    gap: '6px'
                                }}>
                                    {renderNodeIcon(node)}
                                    <span style={{
                                        fontSize: '13px',
                                        color: '#262626',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap',
                                    }}>{node.nodeName}({node.nodeType})</span>
                                </div>
                            </div>
                        </Tooltip>
                    ))}
                </div>
            )
        }));

    return (
        <Card
            title="流程节点"
            size="small"
            loading={loading}
            styles={{
                header: {
                    padding: '12px 16px',
                    fontSize: '15px',
                    fontWeight: 500,
                    borderBottom: '1px solid #f0f0f0',
                },
                body: {
                    padding: '12px',
                    height: 'calc(100vh - 250px)',
                    overflowY: 'auto',
                    overflowX: 'hidden'
                }
            }}
        >
            <Collapse
                defaultActiveKey={['1', '2', '3', '4']}
                ghost
                items={collapseItems}
                style={{
                    background: 'transparent',
                }}
            />
        </Card>
    );
};

export default NodePanel;
