import React, { useState, useMemo, useCallback } from 'react';
import { useReactFlow } from '@xyflow/react';
import { SmartStepEdge as BaseSmartEdge } from '@tisoap/react-flow-smart-edge';
import type { FlowNode } from '../types';
import { convertToDisplayName } from '@/utils/workflow/variableConversion';

/**
 * 自定义边组件 - 智能避障
 * 使用 SmartStepEdge 实现智能路由避障，采用直角路径
 * 
 * 便捷功能：
 * - 选中高亮显示
 * - 悬停状态反馈
 * - 双击重置为默认路径
 */
const CustomEdge: React.FC<any> = (props) => {
    const {
        id,
        style = {},
        markerEnd,
        label,
        selected,
        ...restProps
    } = props;

    const [isHovered, setIsHovered] = useState(false);
    const { getNodes, setEdges } = useReactFlow();

    // 将 label 中的 UUID 转换为节点名
    const displayLabel = useMemo(() => {
        if (!label || typeof label !== 'string') {
            return label;
        }

        const allNodes = getNodes() as FlowNode[];
        return convertToDisplayName(label, allNodes);
    }, [label, getNodes]);

    // 根据状态确定样式
    const edgeStyle = {
        ...style,
        stroke: selected ? '#3b82f6' : isHovered ? '#64748b' : '#94a3b8',
        strokeWidth: selected ? 3 : isHovered ? 2.5 : 2,
        transition: 'all 0.2s ease',
    };

    const markerEndStyle = (() => {
        if (!markerEnd || typeof markerEnd !== 'object') return markerEnd;
        const markerObj = markerEnd as Record<string, any>;
        if (selected) return { ...markerObj, color: '#3b82f6' };
        if (isHovered) return { ...markerObj, color: '#64748b' };
        return markerEnd;
    })();

    // 自定义标签样式
    const labelStyle = {
        fill: selected ? '#3b82f6' : '#64748b',
        fontWeight: 500,
        fontSize: 12,
    };

    const labelBgStyle = {
        fill: 'white',
        fillOpacity: 1,
    };

    const labelBgPadding = [4, 8] as [number, number];
    const labelBgBorderRadius = 6;

    /**
     * 双击边重置为默认路径
     * 清除所有自定义调整，恢复到库的默认智能路由
     */
    const handleDoubleClick = useCallback((e: React.MouseEvent) => {
        e.stopPropagation();
        setEdges(eds => eds.map(ed => {
            if (ed.id !== id) return ed;
            // 清除可能存储的自定义路径数据
            const { vertices, ...restData } = (ed.data || {}) as any;
            return { ...ed, data: restData };
        }));
    }, [id, setEdges]);

    return (
        <g
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            onDoubleClick={handleDoubleClick}
            style={{ cursor: selected ? 'pointer' : 'default' }}
        >
            <BaseSmartEdge
                {...restProps}
                label={displayLabel}
                style={edgeStyle}
                markerEnd={markerEndStyle as any}
                labelStyle={labelStyle}
                labelBgStyle={labelBgStyle}
                labelBgPadding={labelBgPadding}
                labelBgBorderRadius={labelBgBorderRadius}
            />
        </g>
    );
};

export default CustomEdge;

