
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { CrawlingResponse, TargetPersona, SellingPoint } from '../../types/api';

interface AnalysisResultSectionProps {
  onBack: () => void;
  onGenerate?: () => void;
  data: CrawlingResponse;
}

// 레이더 차트 컴포넌트
interface RadarChartProps {
  data: SellingPoint[];
  size?: number;
}

const RadarChart: React.FC<RadarChartProps> = ({ data, size = 360 }) => {
  const [animatedScores, setAnimatedScores] = useState<number[]>(data.map(() => 0));
  const [isAnimating, setIsAnimating] = useState(true);

  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);

      const newScores = targetScores.map(target => target * easeProgress);
      setAnimatedScores(newScores);

      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        setIsAnimating(false);
      }
    };

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

  const padding = 80;
  const center = size / 2 + padding;
  const maxRadius = size / 2 - 20;
  const levels = 5;
  const angleStep = (2 * Math.PI) / data.length;

  const getPoint = (index: number, score: number) => {
    const angle = angleStep * index - Math.PI / 2;
    const radius = (score / 100) * maxRadius;
    return {
      x: center + radius * Math.cos(angle),
      y: center + radius * Math.sin(angle),
    };
  };

  const dataPoints = animatedScores.map((score, i) => getPoint(i, score));
  const dataPath = dataPoints.map((p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`)).join(' ') + ' Z';

  const levelPaths = Array.from({ length: levels }, (_, levelIndex) => {
    const levelRadius = ((levelIndex + 1) / levels) * maxRadius;
    const points = data.map((_, i) => {
      const angle = angleStep * i - Math.PI / 2;
      return {
        x: center + levelRadius * Math.cos(angle),
        y: center + levelRadius * Math.sin(angle),
      };
    });
    return points.map((p, i) => (i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`)).join(' ') + ' Z';
  });

  const axisLines = data.map((_, i) => {
    const angle = angleStep * i - Math.PI / 2;
    const endX = center + maxRadius * Math.cos(angle);
    const endY = center + maxRadius * Math.sin(angle);
    return `M ${center} ${center} L ${endX} ${endY}`;
  });

  const svgSize = size + padding * 2;

  // 순위별로 정렬하여 라벨 위치에 순위 번호 배치
  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));

  return (
    <div className="bi2-radar-container">
      <svg
        width={svgSize}
        height={svgSize}
        viewBox={`0 0 ${svgSize} ${svgSize}`}
        style={{ overflow: 'visible' }}
      >
        {levelPaths.map((path, i) => (
          <path
            key={`level-${i}`}
            d={path}
            fill="none"
            stroke="rgba(255,255,255,0.2)"
            strokeWidth="1"
          />
        ))}

        {axisLines.map((path, i) => (
          <path
            key={`axis-${i}`}
            d={path}
            fill="none"
            stroke="rgba(255,255,255,0.2)"
            strokeWidth="1"
          />
        ))}

        <path
          d={dataPath}
          fill="rgba(45, 212, 191, 0.2)"
          stroke="#2DD4BF"
          strokeWidth="2"
          style={{
            transition: isAnimating ? 'none' : 'd 0.3s ease-out',
          }}
        />

        {dataPoints.map((point, i) => (
          <circle
            key={`point-${i}`}
            cx={point.x}
            cy={point.y}
            r="4"
            fill="#2DD4BF"
            stroke="#1A1A2E"
            strokeWidth="2"
          />
        ))}

        {data.map((item, i) => {
          const angle = angleStep * i - Math.PI / 2;
          const labelRadius = maxRadius + 40;
          const pos = {
            x: center + labelRadius * Math.cos(angle),
            y: center + labelRadius * Math.sin(angle),
          };
          const rank = rankMap.get(i) || i + 1;
          const isTopThree = rank <= 3;

          return (
            <g key={`label-${i}`}>
              <g transform={`translate(${pos.x}, ${pos.y})`}>
                <rect
                  x="-10"
                  y="-10"
                  width="20"
                  height="20"
                  rx="4"
                  fill={isTopThree ? '#94FBE0' : '#206764'}
                />
                <text
                  x="0"
                  y="0"
                  textAnchor="middle"
                  dominantBaseline="central"
                  style={{
                    fontSize: '12px',
                    fontWeight: 600,
                    fill: isTopThree ? '#002224' : '#94FBE0',
                    fontFamily: 'Pretendard',
                  }}
                >
                  {rank}
                </text>
                <text
                  x="16"
                  y="0"
                  textAnchor="start"
                  dominantBaseline="central"
                  style={{
                    fontSize: '14px',
                    fontWeight: 400,
                    fill: '#E5F1F2',
                    fontFamily: 'Pretendard',
                  }}
                >
                  {item.korean_category}
                </text>
              </g>
            </g>
          );
        })}
      </svg>
    </div>
  );
};

const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, onGenerate, data }) => {
  const { t } = useTranslation();
  const { processed_info, marketing_analysis } = data;
  const containerRef = useRef<HTMLDivElement>(null);
  const [buttonPosition, setButtonPosition] = useState({ left: 0, width: 0 });

  const brandIdentity = marketing_analysis?.brand_identity;
  const marketPositioning = marketing_analysis?.market_positioning;
  const targetPersonas = marketing_analysis?.target_persona || [];
  const sellingPoints = marketing_analysis?.selling_points || [];
  const targetKeywords = marketing_analysis?.target_keywords || [];

  // 셀링 포인트를 score 내림차순으로 정렬
  const sortedSellingPoints = [...sellingPoints].sort((a, b) => b.score - a.score);

  useEffect(() => {
    const updateButtonPosition = () => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        setButtonPosition({ left: rect.left, width: rect.width });
      }
    };

    updateButtonPosition();
    window.addEventListener('resize', updateButtonPosition);

    const observer = new MutationObserver(updateButtonPosition);
    observer.observe(document.body, { attributes: true, subtree: true, attributeFilter: ['class'] });

    return () => {
      window.removeEventListener('resize', updateButtonPosition);
      observer.disconnect();
    };
  }, []);

  return (
    <div className="bi2-page">
      {/* Header */}
      <div className="bi2-header">
        <button onClick={onBack} className="bi2-back-btn">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M15 18l-6-6 6-6" />
          </svg>
          <span>{t('analysis.back')}</span>
        </button>
      </div>

      {/* Page Title */}
      <div className="bi2-page-title-section">
        <div className="bi2-title-icon">
          <img src="/assets/images/star-icon.svg" alt="" className="bi2-star-icon" />
        </div>
        <div className="bi2-title-text">
          <h1 className="bi2-main-title">{t('analysis.pageTitle')}</h1>
          <p className="bi2-subtitle">
            {t('analysis.pageDescHighlight')}{t('analysis.pageDescBefore')}{processed_info?.customer_name || t('analysis.defaultBrandName')}{t('analysis.pageDescAfter')}
          </p>
        </div>
      </div>

      {/* Main Content Container */}
      <div ref={containerRef} className="bi2-main-container">
        {/* 매장명 & 주소 */}
        <div className="bi2-store-header">
          <h2 className="bi2-store-name">{processed_info?.customer_name || t('analysis.brandNameFallback')}</h2>
          <p className="bi2-store-address">{processed_info?.detail_region_info || t('analysis.addressFallback')}</p>
        </div>

        {/* 브랜드 정체성 */}
        <div className="bi2-section">
          <h3 className="bi2-section-title">{t('analysis.brandIdentity')}</h3>
          <div className="bi2-identity-card">
            <div className="bi2-identity-top">
              <div className="bi2-identity-core">
                <span className="bi2-label-sm">{t('analysis.coreValue')}</span>
                <p className="bi2-core-value">{marketPositioning?.core_value || t('analysis.noInfo')}</p>
              </div>
              <p className="bi2-category-text">{t('analysis.categoryDefinition')} : {marketPositioning?.category_definition || t('analysis.noInfo')}</p>
            </div>
            <div className="bi2-identity-divider"></div>
            <div className="bi2-identity-bottom">
              <div className="bi2-identity-col">
                <span className="bi2-label-sm">{t('analysis.locationAnalysis')}</span>
                <p className="bi2-body-text">{brandIdentity?.location_feature_analysis || t('analysis.noInfo')}</p>
              </div>
              <div className="bi2-identity-col">
                <span className="bi2-label-sm">{t('analysis.conceptScalability')}</span>
                <p className="bi2-body-text">{brandIdentity?.concept_scalability || t('analysis.noInfo')}</p>
              </div>
            </div>
          </div>
        </div>

        {/* 주요 셀링 포인트 */}
        <div className="bi2-section">
          <h3 className="bi2-section-title">{t('analysis.sellingPoints')}</h3>
          <div className="bi2-selling-card">
            {/* 레이더 차트 */}
            <div className="bi2-selling-chart">
              {sellingPoints.length > 0 && (
                <RadarChart data={sellingPoints} size={360} />
              )}
            </div>
            {/* 셀링 포인트 리스트 */}
            <div className="bi2-selling-list">
              {sortedSellingPoints.map((sp, idx) => {
                const rank = idx + 1;
                const isTopThree = rank <= 3;
                return (
                  <div key={idx} className="bi2-selling-item">
                    <div className={`bi2-rank-badge ${isTopThree ? 'top' : ''}`}>
                      {rank}
                    </div>
                    <div className="bi2-selling-item-text">
                      <span className="bi2-selling-name">{sp.korean_category}</span>
                      <span className="bi2-selling-desc">{sp.description}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* 주요 고객 유형 */}
        <div className="bi2-section">
          <h3 className="bi2-section-title">{t('analysis.targetPersona')}</h3>
          <div className="bi2-persona-grid">
            {targetPersonas.map((persona: TargetPersona, idx: number) => (
              <div key={idx} className="bi2-persona-card">
                <div className="bi2-persona-header">
                  <div className="bi2-persona-info">
                    <span className="bi2-persona-name">{persona.persona}</span>
                    <span className="bi2-persona-age">{persona.age.min_age}~{persona.age.max_age}{t('analysis.ageSuffix')}</span>
                  </div>
                  <p className="bi2-persona-desc">
                    {persona.decision_trigger}
                  </p>
                </div>
                <div className="bi2-persona-divider"></div>
                <div className="bi2-persona-detail grow">
                  <span className="bi2-label-xs">{t('analysis.favorKeywords', { defaultValue: '선호 키워드' })}</span>
                  <p className="bi2-persona-detail-text">
                    {persona.favor_target.join('\n')}
                  </p>
                </div>
                <div className="bi2-persona-divider"></div>
                <div className="bi2-persona-detail">
                  <span className="bi2-label-xs">{t('analysis.decisionTrigger', { defaultValue: '예약 결정 포인트' })}</span>
                  <p className="bi2-persona-detail-text">{persona.decision_trigger}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 추천 타겟 키워드 */}
        <div className="bi2-section">
          <div className="bi2-keyword-header">
            <h3 className="bi2-section-title">{t('analysis.recommendedKeywords')}</h3>
            <p className="bi2-keyword-subtitle">{t('analysis.keywordHint', { defaultValue: '이런 키워드로 찾을 가능성이 높아요' })}</p>
          </div>
          <div className="bi2-keyword-tags">
            {targetKeywords.map((keyword: string, idx: number) => (
              <span key={idx} className="bi2-keyword-pill">#{keyword}</span>
            ))}
          </div>
        </div>
      </div>

      {/* 콘텐츠 생성 버튼 */}
      <div
        className="fixed bottom-8 flex justify-center z-50 pointer-events-none"
        style={{ left: buttonPosition.left, width: buttonPosition.width }}
      >
        <button
          onClick={onGenerate}
          className="pointer-events-auto bg-brand-purple hover:bg-brand-purpleHover text-white font-bold py-3 px-12 rounded-full shadow-2xl shadow-brand-purple/40 transform hover:scale-105 transition-all duration-300 flex items-center gap-2"
        >
          <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden className="w-5 h-5">
            <path d="M12 2l2.4 6.8L22 12l-7.6 3.2L12 22l-2.4-6.8L2 12l7.6-3.2L12 2z" />
          </svg>
          {t('analysis.generateContent')}
        </button>
      </div>
    </div>
  );
};

export default AnalysisResultSection;
