import { useState, useMemo } from 'react';

interface NetworkNode {
  cui: string;
  name: string;
  contracts: number;
  total_value: number;
  side: 'authority' | 'supplier';
  others?: { cui: string; name: string; contracts: number; total_value: number }[];
}

interface NetworkData {
  center: NetworkNode;
  neighbors: NetworkNode[];
}

interface Props {
  data: NetworkData;
}

function formatRON(v: number): string {
  if (!Number.isFinite(v) || v <= 0) return '0';
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(1)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
}

function shortName(s: string, n: number = 30): string {
  return s.length > n ? s.slice(0, n - 1) + '…' : s;
}

export function NetworkGraph({ data }: Props) {
  const [hoverIdx, setHoverIdx] = useState<number | null>(null);
  const [pinnedIdx, setPinnedIdx] = useState<number | null>(null);

  const W = 760, H = 700;
  const cx = W / 2, cy = H / 2;
  const radius = 240;

  const layout = useMemo(() => {
    const max = Math.max(...data.neighbors.map((n) => n.total_value), 1);
    return data.neighbors.map((n, i) => {
      // Spiral-ish layout with two rings: top 10 inner, rest outer
      const isInner = i < 10;
      const ringRadius = isInner ? radius * 0.85 : radius * 1.15;
      const ringSize = isInner ? Math.min(10, data.neighbors.length) : data.neighbors.length - 10;
      const idxInRing = isInner ? i : i - 10;
      const angle = (idxInRing / Math.max(ringSize, 1)) * Math.PI * 2 - Math.PI / 2;
      const ratio = Math.sqrt(n.total_value / max);
      return {
        node: n,
        x: cx + Math.cos(angle) * ringRadius,
        y: cy + Math.sin(angle) * ringRadius,
        r: 6 + ratio * 24,
        ratio,
      };
    });
  }, [data, cx, cy, radius]);

  const isAuthorityCenter = data.center.side === 'authority';
  const centerColor = isAuthorityCenter ? '#0F172A' : '#1D4ED8';
  const neighborColor = isAuthorityCenter ? '#1D4ED8' : '#0F172A';
  const edgeColor = 'rgba(37, 99, 235, 0.4)';

  const activeIdx = pinnedIdx ?? hoverIdx;
  const activeNode = activeIdx != null ? layout[activeIdx] : null;

  return (
    <div className="profile-network">
      <div className="profile-network-toolbar">
        <span className="label-meta">
          {isAuthorityCenter
            ? `Top ${data.neighbors.length} furnizori care lucrează cu autoritatea`
            : `Top ${data.neighbors.length} autorități pentru această firmă`}
        </span>
        {pinnedIdx != null && (
          <button onClick={() => setPinnedIdx(null)} className="profile-network-clear">
            Închide detaliu
          </button>
        )}
      </div>

      <div className="profile-network-canvas-wrap">
        <svg viewBox={`0 0 ${W} ${H}`} className="profile-network-svg">
          {/* Edges from center */}
          {layout.map((l, i) => (
            <line
              key={`e-${i}`}
              x1={cx} y1={cy} x2={l.x} y2={l.y}
              stroke={edgeColor}
              strokeWidth={0.5 + l.ratio * 2.5}
              strokeOpacity={activeIdx == null || activeIdx === i ? 1 : 0.2}
            />
          ))}

          {/* Active node's "other authorities/suppliers" — second ring */}
          {activeNode && activeNode.node.others && activeNode.node.others.map((o, j) => {
            const others = activeNode.node.others!;
            // Position around the active neighbor
            const dx = activeNode.x - cx;
            const dy = activeNode.y - cy;
            const len = Math.sqrt(dx * dx + dy * dy) || 1;
            const ux = dx / len, uy = dy / len;
            const perpX = -uy, perpY = ux;

            const oCount = others.length;
            const angleOffset = (j - (oCount - 1) / 2) * 0.4;
            const ax = activeNode.x + ux * 60 + perpX * angleOffset * 50;
            const ay = activeNode.y + uy * 60 + perpY * angleOffset * 50;

            return (
              <g key={`o-${j}`}>
                <line
                  x1={activeNode.x} y1={activeNode.y} x2={ax} y2={ay}
                  stroke="rgba(180, 83, 9, 0.5)" strokeWidth="1.2" strokeDasharray="2 3"
                />
                <circle cx={ax} cy={ay} r="6" fill="white" stroke="#B45309" strokeWidth="1.5" />
                <rect x={ax - 100} y={ay + 10} width="200" height="22" fill="rgba(15,23,42,0.92)" rx="4" />
                <text x={ax} y={ay + 22} fontSize="9" fill="white" textAnchor="middle" fontFamily="Inter, system-ui, sans-serif">
                  {shortName(o.name, 28)}
                </text>
                <text x={ax} y={ay + 30} fontSize="8.5" fill="rgba(255,255,255,0.7)" textAnchor="middle" fontFamily="Inter, system-ui, sans-serif">
                  {o.contracts} contracte · {formatRON(o.total_value)}
                </text>
              </g>
            );
          })}

          {/* Neighbor nodes */}
          {layout.map((l, i) => (
            <g
              key={`n-${i}`}
              onMouseEnter={() => setHoverIdx(i)}
              onMouseLeave={() => setHoverIdx(null)}
              onClick={() => setPinnedIdx(pinnedIdx === i ? null : i)}
              style={{ cursor: 'pointer' }}
            >
              <circle
                cx={l.x} cy={l.y} r={l.r}
                fill="white"
                stroke={neighborColor}
                strokeWidth={activeIdx === i ? 3 : 2}
                opacity={activeIdx == null || activeIdx === i ? 1 : 0.4}
              />
              {(activeIdx === i || (activeIdx == null && i < 5)) && (
                <text
                  x={l.x} y={l.y - l.r - 6}
                  textAnchor="middle"
                  fontSize="11"
                  fontFamily="Plus Jakarta Sans, system-ui, sans-serif"
                  fontWeight="600"
                  fill="#0F172A"
                >
                  {shortName(l.node.name, 24)}
                </text>
              )}
            </g>
          ))}

          {/* Center node */}
          <g>
            <circle cx={cx} cy={cy} r="46" fill="rgba(15,23,42,0.05)" />
            <circle cx={cx} cy={cy} r="32" fill={centerColor} />
            <text
              x={cx} y={cy + 1}
              textAnchor="middle"
              fontSize="22"
              fill="white"
              fontFamily="Plus Jakarta Sans, system-ui, sans-serif"
              fontWeight="800"
            >
              {isAuthorityCenter ? '🏛' : '🏭'}
            </text>
            <text
              x={cx} y={cy + 50}
              textAnchor="middle"
              fontSize="13"
              fontFamily="Plus Jakarta Sans, system-ui, sans-serif"
              fontWeight="700"
              fill="#0F172A"
            >
              {shortName(data.center.name, 36)}
            </text>
            <text
              x={cx} y={cy + 66}
              textAnchor="middle"
              fontSize="11"
              fill="#64748B"
            >
              CUI {data.center.cui} · {data.center.contracts} contracte · {formatRON(data.center.total_value)} RON
            </text>
          </g>
        </svg>
      </div>

      {activeNode && (
        <div className="profile-network-detail">
          <div className="profile-network-detail-header">
            <div>
              <div className="label-meta">{isAuthorityCenter ? 'Furnizor' : 'Autoritate'}</div>
              <a href={`/${activeNode.node.side === 'supplier' ? 'firma' : 'autoritate'}/${activeNode.node.cui}`} className="profile-network-detail-name">
                {activeNode.node.name}
              </a>
              <div className="profile-network-detail-sub">
                CUI {activeNode.node.cui} · {activeNode.node.contracts} contracte · {formatRON(activeNode.node.total_value)} RON
              </div>
            </div>
          </div>

          {activeNode.node.others && activeNode.node.others.length > 0 && (
            <div className="profile-network-detail-others">
              <div className="label-meta">
                Alte {isAuthorityCenter ? 'autorități' : 'firme'} cu care lucrează
              </div>
              <div className="profile-network-detail-list">
                {activeNode.node.others.map((o, j) => (
                  <a
                    key={j}
                    href={`/${isAuthorityCenter ? 'autoritate' : 'firma'}/${o.cui}`}
                    className="profile-network-detail-item"
                  >
                    <span className="profile-network-detail-item-name">{o.name}</span>
                    <span className="profile-network-detail-item-meta">
                      {o.contracts} · {formatRON(o.total_value)}
                    </span>
                  </a>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
