import React, { useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import {
  ReactFlow,
  type Node,
  type Edge,
  Controls,
  Background,
  useNodesState,
  useEdgesState,
  ConnectionMode,
  Panel,
  Handle,
  Position,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import { Box, Typography, Alert, Chip, Card, CardContent, Tooltip, Avatar } from '@mui/material';
import type { IKnowledgeGraph } from '@/interfaces/database/knowledge';
import { v4 as uuidv4 } from 'uuid';

interface KnowledgeGraphProps {
  knowledgeGraph?: IKnowledgeGraph | null;
}

// 根据实体类型获取节点颜色
const getNodeColor = (entityType?: string): string => {
  const colorMap: Record<string, string> = {
    PERSON: '#FF6B6B',      // 红色 - 人物
    ORGANIZATION: '#4ECDC4', // 青色 - 组织
    LOCATION: '#45B7D1',     // 蓝色 - 地点
    EVENT: '#96CEB4',        // 绿色 - 事件
    CONCEPT: '#FFEAA7',      // 黄色 - 概念
    CATEGORY: '#DDA0DD',     // 紫色 - 分类
    TECHNOLOGY: '#98D8C8',   // 薄荷绿 - 技术
    PRODUCT: '#F7DC6F',      // 金黄色 - 产品
    SERVICE: '#BB8FCE',      // 淡紫色 - 服务
  };
  return colorMap[entityType || 'CONCEPT'] || '#74B9FF';
};

// 自定义节点组件
const CustomNode = ({ data }: { data: any }) => {
  const { t } = useTranslation();
  const nodeColor = getNodeColor(data.entity_type);
  const nodeSize = Math.max(80, Math.min(140, (data.pagerank || 0.1) * 500));
  
  // 获取节点首字母作为Avatar显示
  const getInitials = (name: string) => {
    if (!name) return '?';
    const words = name.trim().split(/\s+/);
    if (words.length === 1) {
      return words[0].charAt(0).toUpperCase();
    }
    return words.slice(0, 2).map(word => word.charAt(0).toUpperCase()).join('');
  };

  const tooltipContent = (
    <Box sx={{ p: 1, maxWidth: 300 }}>
      <Typography variant="subtitle2" sx={{ fontWeight: 'bold', mb: 1 }}>
        {data.label || data.name || t('knowledge.unknown')}
      </Typography>
      <Typography variant="body2" sx={{ mb: 0.5 }}>
        <strong>{t('knowledge.type')}:</strong> {data.entity_type || t('knowledge.unknown')}
      </Typography>
      {data.description && (
        <Typography variant="body2">
          <strong>{t('knowledge.description')}:</strong> {data.description}
        </Typography>
      )}
      {data.pagerank && (
        <Typography variant="caption" sx={{ display: 'block', mt: 1 }}>
          {t('knowledge.pageRank')}: {data.pagerank.toFixed(4)}
        </Typography>
      )}
    </Box>
  );

  return (
    <Tooltip 
      title={tooltipContent} 
      placement="top"
      arrow
      enterDelay={500}
      leaveDelay={200}
    >
      <Card
        sx={{
          width: nodeSize,
          height: nodeSize,
          borderRadius: '50%',
          border: '3px solid #fff',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          cursor: 'pointer',
          position: 'relative',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: nodeColor,
          transition: 'all 0.2s ease-in-out',
          '&:hover': {
            transform: 'scale(1.1)',
            boxShadow: '0 6px 20px rgba(0,0,0,0.25)',
            zIndex: 10,
          },
        }}
      >
        {/* React Flow Handle 组件 */}
        <Handle
          type="target"
          position={Position.Top}
          style={{ background: '#555', opacity: 0 }}
        />
        <Handle
          type="source"
          position={Position.Bottom}
          style={{ background: '#555', opacity: 0 }}
        />
        
        <CardContent
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            p: 1,
            '&:last-child': { pb: 1 },
            height: '100%',
            width: '100%',
          }}
        >
          <Typography
              variant="caption"
              sx={{
                color: '#fff',
                fontWeight: 'bold',
                fontSize: Math.max(10, nodeSize * 0.08),
                textAlign: 'center',
                lineHeight: 1.1,
                wordBreak: 'break-word',
                textShadow: '1px 1px 2px rgba(0,0,0,0.7)',
                maxWidth: '90%',
                overflow: 'hidden',
                display: '-webkit-box',
                WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
              }}
            >
              {data.label || data.name || t('knowledge.unknown')}
            </Typography>
        </CardContent>
      </Card>
    </Tooltip>
  );
};

const nodeTypes = {
  custom: CustomNode,
};

const KnowledgeGraphView: React.FC<KnowledgeGraphProps> = ({ knowledgeGraph }) => {
  const { t } = useTranslation();
  
  // 转换数据格式为 React Flow 所需的格式
  const { nodes: initialNodes, edges: initialEdges } = useMemo(() => {
    const graphData = knowledgeGraph?.graph || {};
    if (!graphData?.nodes || !graphData?.edges) {
      return { nodes: [], edges: [] };
    }

    // 转换节点数据
    // @ts-ignore
    const nodes: Node[] = graphData.nodes.map((node, index) => {
      const encodeId = encodeURIComponent(String(node.id));

      const n: Node = {
        id: encodeId,
        type: 'custom',
        position: {
          x: Math.random() * 800,
          y: Math.random() * 600,
        },
        data: {
          label: node.entity_name || node.id,
          entity_type: node.entity_type,
          pagerank: node.pagerank,
          description: node.description,
          ...node,
        },
      };
      return n
    });

    // 转换边数据
    // @ts-ignore
    const edges: Edge[] = graphData.edges.map((edge, index) => {
      console.log(`${t('knowledge.edge')} ${index}:`, edge);
      console.log(`src_id: ${edge.src_id}, tgt_id: ${edge.tgt_id}`);
      // 检查source和target是否存在
      if (!edge.src_id || !edge.tgt_id) {
        console.warn(`${t('knowledge.edge')} ${index} ${t('knowledge.missingIds')}:`, edge);
        return null;
      }

      // 检查对应的节点是否存在
      const sourceExists = nodes.some(node => node.id === encodeURIComponent(edge.src_id));
      const targetExists = nodes.some(node => node.id === encodeURIComponent(edge.tgt_id));

      if (!sourceExists || !targetExists) {
        console.warn(`${t('knowledge.edge')} ${index} ${t('knowledge.nodeNotExists')}: source=${sourceExists}, target=${targetExists}`, edge);
        return null;
      }

      const weight = Number(edge.weight) || 1;
      const strokeWidth = Math.max(1, Math.min(3, weight));

      const sourceId = encodeURIComponent(String(edge.src_id));
      const targetId = encodeURIComponent(String(edge.tgt_id));

      const edgeObj: Edge = {
        id: `${sourceId}-${targetId}`,
        source: sourceId,
        target: targetId,
        type: 'simplebezier',
        // animated: weight > 5,
        style: {
          strokeWidth,
          stroke: '#99ADD1',
        },
        // label: edge.description ? edge.description.substring(0, 50) + '...' : '',
        labelStyle: {
          fontSize: '10px',
          fill: '#666',
        },
        data: {
          weight: edge.weight,
          description: edge.description,
          keywords: edge.keywords,
        },
      };
      return edgeObj;
    })
      // @ts-ignore
      .filter(edge => edge != null); // 过滤掉null值
    return { nodes, edges };
  }, [knowledgeGraph]);

  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);

  console.log('转换后的节点:', nodes);
  console.log('转换后的边:', edges);
  // 节点点击事件
  const onNodeClick = useCallback((event: React.MouseEvent, node: Node) => {
    console.log('节点点击:', node.data);
  }, []);

  // 边点击事件
  const onEdgeClick = useCallback((event: React.MouseEvent, edge: Edge) => {
    console.log('边点击:', edge.data);
  }, []);

  if (!knowledgeGraph || initialNodes.length === 0) {
    return (
      <Box sx={{ p: 2, display: 'flex', justifyContent: 'center', alignItems: 'center', height: 400 }}>
        <Alert severity="info">{t('knowledge.noGraphData')}</Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ width: '100%', height: '600px', border: '1px solid #e0e0e0', borderRadius: 1 }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onNodeClick={onNodeClick}
        onEdgeClick={onEdgeClick}
        nodeTypes={nodeTypes}
        connectionMode={ConnectionMode.Loose}
        fitView
        fitViewOptions={{ padding: 0.2 }}
        minZoom={0.1}
        maxZoom={2}
      >
        <Background />
        <Controls />

        {/* 图例面板 */}
        <Panel position="top-right">
          <Box sx={{
            backgroundColor: 'rgba(255,255,255,0.9)',
            p: 2,
            borderRadius: 1,
            minWidth: 200,
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
              {t('knowledge.legend')}
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
              {['PERSON', 'ORGANIZATION', 'CATEGORY', 'TECHNOLOGY'].map((type) => (
                <Box key={type} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Box
                    sx={{
                      width: 16,
                      height: 16,
                      borderRadius: '50%',
                      backgroundColor: getNodeColor(type),
                      border: '1px solid #fff',
                    }}
                  />
                  <Typography variant="caption">{type}</Typography>
                </Box>
              ))}
            </Box>
          </Box>
        </Panel>

        {/* 统计信息面板 */}
        <Panel position="top-left">
          <Box sx={{
            backgroundColor: 'rgba(255,255,255,0.9)',
            p: 2,
            borderRadius: 1,
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
              {t('knowledge.graphStats')}
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              <Chip
                label={t('knowledge.nodeCount', { count: nodes.length })}
                size="small"
                color="primary"
                variant="outlined"
              />
              <Chip
                label={t('knowledge.edgeCount', { count: edges.length })}
                size="small"
                color="secondary"
                variant="outlined"
              />
            </Box>
          </Box>
        </Panel>
      </ReactFlow>
    </Box>
  );
};

export default KnowledgeGraphView;
