import React, { useState, useEffect } from 'react';
import { SellingPoint } from '../../types/api';

interface GeometricChartProps {
  data: SellingPoint[];
}

export const GeometricChart: React.FC<GeometricChartProps> = ({ data }) => {
  const [animatedScores, setAnimatedScores] = useState<number[]>(data.map(() => 0));

  useEffect(() => {
    const targetScores = data.map(item => item.score);
    const duration = 1500;
    const startTime = Date.now();

    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const easeProgress = 1 - Math.pow(1 - progress, 3);
      setAnimatedScores(targetScores.map(t => t * easeProgress));
      if (progress < 1) requestAnimationFrame(animate);
    };

    requestAnimationFrame(animate);
  }, [data]);

  const size = 560;
  const center = size / 2;
  const maxRadius = 160;
  const sides = data.length;
  const levels = 5;
  const angleStep = (Math.PI * 2) / sides;

  const getAngle = (i: number) => angleStep * i - Math.PI / 2;
  const getPoint = (i: number, r: number) => ({
    x: center + r * Math.cos(getAngle(i)),
    y: center + r * Math.sin(getAngle(i)),
  });

  // 순위 매핑
  const sortedIndices = [...data]
    .map((item, i) => ({ index: i, score: item.score }))
    .sort((a, b) => b.score - a.score)
    .map((item, rank) => ({ ...item, rank: rank + 1 }));
  const rankMap = new Map<number, number>();
  sortedIndices.forEach(item => rankMap.set(item.index, item.rank));

  // 레벨 폴리곤
  const levelPolygons = Array.from({ length: levels }, (_, li) => {
    const r = ((li + 1) / levels) * maxRadius;
    return data.map((_, i) => {
      const p = getPoint(i, r);
      return `${p.x},${p.y}`;
    }).join(' ');
  });

  // 데이터 폴리곤
  const dataPolygon = animatedScores.map((score, i) => {
    const r = (score / 100) * maxRadius;
    const p = getPoint(i, r);
    return `${p.x},${p.y}`;
  }).join(' ');

  // 데이터 포인트
  const dataPoints = animatedScores.map((score, i) => {
    const r = (score / 100) * maxRadius;
    return getPoint(i, r);
  });

  const labelRadius = maxRadius + 22;

  return (
    <div className="bi2-radar-container">
      <svg
        viewBox={`0 0 ${size} ${size}`}
        style={{ overflow: 'visible', width: '440px', height: '440px' }}
      >
        <defs>
          {/* 레이더 폴리곤 fill: radial gradient */}
          <radialGradient id="radar-fill-gradient" cx="280" cy="280" r="160" fx="280" fy="280" gradientUnits="userSpaceOnUse">
            <stop offset="60%" stopColor="#034245" stopOpacity="0" />
            <stop offset="100%" stopColor="#94FBE0" stopOpacity="0.30" />
          </radialGradient>
          {/* 레이더 폴리곤 filter: outer drop-shadow + inset glow */}
          <filter id="radar-polygon-filter" x="-30%" y="-30%" width="160%" height="160%">
            {/* Outer drop shadow */}
            <feDropShadow dx="0" dy="0" stdDeviation="6" floodColor="#94FBE0" floodOpacity="0.5" result="dropShadow" />
            {/* Inset glow: invert alpha → blur → composite inside */}
            <feComponentTransfer in="SourceAlpha" result="invertedAlpha">
              <feFuncA type="linear" slope="-1" intercept="1" />
            </feComponentTransfer>
            <feGaussianBlur in="invertedAlpha" stdDeviation="6" result="blurredOuter" />
            <feComposite in="blurredOuter" in2="SourceAlpha" operator="in" result="insetMask" />
            <feFlood floodColor="#94FBE0" floodOpacity="0.5" result="insetColor" />
            <feComposite in="insetColor" in2="insetMask" operator="in" result="insetGlow" />
            <feMerge>
              <feMergeNode in="dropShadow" />
              <feMergeNode in="SourceGraphic" />
              <feMergeNode in="insetGlow" />
            </feMerge>
          </filter>
          <filter id="badge-glow" x="-50%" y="-50%" width="200%" height="200%">
            <feDropShadow dx="0" dy="0" stdDeviation="4" floodColor="#94FBE0" floodOpacity="0.4" />
          </filter>
        </defs>

        {/* 그리드 레벨 */}
        {levelPolygons.map((points, i) => (
          <polygon
            key={`level-${i}`}
            points={points}
            fill="none"
            stroke="rgba(255,255,255,0.2)"
            strokeWidth="1"
          />
        ))}

        {/* 축 선 */}
        {data.map((_, i) => {
          const p = getPoint(i, maxRadius);
          return (
            <line
              key={`axis-${i}`}
              x1={center}
              y1={center}
              x2={p.x}
              y2={p.y}
              stroke="rgba(255,255,255,0.2)"
              strokeWidth="1"
            />
          );
        })}

        {/* 데이터 폴리곤 */}
        <polygon
          points={dataPolygon}
          fill="url(#radar-fill-gradient)"
          stroke="var(--Color-mint-500, #94FBE0)"
          strokeWidth="2"
          strokeLinejoin="round"
          filter="url(#radar-polygon-filter)"
        />

        {/* 데이터 포인트 */}
        {dataPoints.map((point, i) => (
          <circle
            key={`point-${i}`}
            cx={point.x}
            cy={point.y}
            r="4"
            fill="#ffffff"
            stroke="#ffffff"
            strokeWidth="2"
          />
        ))}

        {/* 라벨 */}
        {data.map((item, i) => {
          const angle = getAngle(i);
          const pos = getPoint(i, labelRadius);
          const rank = rankMap.get(i) || i + 1;
          const isTopThree = rank <= 3;
          const isLeftSide = Math.cos(angle) < -0.1;
          const textX = isLeftSide ? -20 : 20;
          const textAnchor: 'start' | 'end' = isLeftSide ? 'end' : 'start';

          return (
            <g key={`label-${i}`}>
              <g transform={`translate(${pos.x}, ${pos.y})`}>
                {isLeftSide && (
                  <text
                    x={textX}
                    y="0"
                    textAnchor={textAnchor}
                    dominantBaseline="central"
                    className="bi2-radar-label-text"
                    style={{ fontSize: '20px', fontWeight: 600, fill: '#E5F1F2', fontFamily: 'Pretendard' }}
                  >
                    {item.korean_category}
                  </text>
                )}
                <g filter={isTopThree ? 'url(#badge-glow)' : undefined}>
                  <rect x="-12.5" y="-12.5" width="25" height="25" rx="4" fill={isTopThree ? '#94FBE0' : '#206764'} />
                  <text
                    x="0" y="0"
                    textAnchor="middle"
                    dominantBaseline="central"
                    style={{ fontSize: '16px', fontWeight: 600, fill: isTopThree ? '#002224' : '#94FBE0', fontFamily: 'Pretendard' }}
                  >
                    {rank}
                  </text>
                </g>
                {!isLeftSide && (
                  <text
                    x={textX}
                    y="0"
                    textAnchor={textAnchor}
                    dominantBaseline="central"
                    className="bi2-radar-label-text"
                    style={{ fontSize: '20px', fontWeight: 600, fill: '#E5F1F2', fontFamily: 'Pretendard' }}
                  >
                    {item.korean_category}
                  </text>
                )}
              </g>
            </g>
          );
        })}
      </svg>
    </div>
  );
};

export default GeometricChart;
