import React from 'react';
import type { GraphEdge, GraphNode } from '../../../types/research';

interface ResearchGraphProps {
  nodes: GraphNode[];
  edges: GraphEdge[];
  selectedNodeId?: string;
  onSelectNode: (nodeId: string) => void;
}

const polarPosition = (index: number, total: number, radius: number) => {
  const angle = (Math.PI * 2 * index) / Math.max(total, 1) - Math.PI / 2;
  return {
    x: 420 + radius * Math.cos(angle),
    y: 320 + radius * Math.sin(angle),
  };
};

export const ResearchGraph: React.FC<ResearchGraphProps> = ({
  nodes,
  edges,
  selectedNodeId,
  onSelectNode,
}) => {
  const positionedNodes = nodes.map((node, index) => ({
    ...node,
    ...polarPosition(index, nodes.length, 220),
  }));
  const nodeMap = new Map(positionedNodes.map((node) => [node.id, node]));

  return (
    <div className="overflow-hidden rounded-[28px] border border-term-border bg-term-bg">
      <svg viewBox="0 0 840 640" className="h-[640px] w-full">
        <defs>
          <radialGradient id="graphGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="#1d443f" stopOpacity="0.72" />
            <stop offset="100%" stopColor="#081016" stopOpacity="0" />
          </radialGradient>
        </defs>
        <rect x="0" y="0" width="840" height="640" fill="url(#graphGlow)" />
        {edges.map((edge) => {
          const from = nodeMap.get(edge.from);
          const to = nodeMap.get(edge.to);
          if (!from || !to) {
            return null;
          }

          return (
            <line
              key={edge.id}
              x1={from.x}
              y1={from.y}
              x2={to.x}
              y2={to.y}
              stroke={edge.linkType === 'contradicts' ? '#ff8895' : '#7fd4c9'}
              strokeWidth={Math.max(1.5, edge.confidence * 4)}
              strokeDasharray={edge.linkType === 'timeframe_conflict' ? '6 6' : undefined}
              opacity={0.65}
            />
          );
        })}
        {positionedNodes.map((node) => (
          <g
            key={node.id}
            onClick={() => onSelectNode(node.id)}
            className="cursor-pointer"
          >
            <circle
              cx={node.x}
              cy={node.y}
              r={selectedNodeId === node.id ? 34 : 28}
              fill={selectedNodeId === node.id ? '#1b3b37' : '#162028'}
              stroke={selectedNodeId === node.id ? '#96ddd2' : '#46606f'}
              strokeWidth={selectedNodeId === node.id ? 2.5 : 1.5}
            />
            <text
              x={node.x}
              y={node.y + 4}
              textAnchor="middle"
              className="fill-[#e7edf4] text-[11px] font-medium"
            >
              {node.label.slice(0, 18)}
            </text>
          </g>
        ))}
      </svg>
    </div>
  );
};
