import { useEffect, useRef, useState } from "react";

export default function PerformanceChart() {
  const sectionRef = useRef<HTMLDivElement>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [animationPhase, setAnimationPhase] = useState(0);
  const [hoveredPoint, setHoveredPoint] = useState<{ x: number; y: number; label: string; value: string } | null>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !isVisible) {
          setIsVisible(true);
        }
      },
      { threshold: 0.4 }
    );

    if (sectionRef.current) {
      observer.observe(sectionRef.current);
    }

    return () => observer.disconnect();
  }, [isVisible]);

  useEffect(() => {
    if (isVisible) {
      const timer1 = setTimeout(() => setAnimationPhase(1), 300);
      const timer2 = setTimeout(() => setAnimationPhase(2), 1800);
      const timer3 = setTimeout(() => setAnimationPhase(3), 3000);
      return () => {
        clearTimeout(timer1);
        clearTimeout(timer2);
        clearTimeout(timer3);
      };
    }
  }, [isVisible]);

  const chartWidth = 600;
  const chartHeight = 340;
  const padding = { left: 70, right: 30, top: 30, bottom: 50 };
  const graphWidth = chartWidth - padding.left - padding.right;
  const graphHeight = chartHeight - padding.top - padding.bottom;

  const yearlyData = [
    { year: 0, invested: 0, portfolio: 0 },
    { year: 1, invested: 1200, portfolio: 1290 },
    { year: 2, invested: 2400, portfolio: 2760 },
    { year: 3, invested: 3600, portfolio: 4440 },
    { year: 4, invested: 4800, portfolio: 6370 },
    { year: 5, invested: 6000, portfolio: 8590 },
    { year: 6, invested: 7200, portfolio: 11150 },
    { year: 7, invested: 8400, portfolio: 14110 },
    { year: 8, invested: 9600, portfolio: 17540 },
    { year: 9, invested: 10800, portfolio: 21520 },
    { year: 10, invested: 12000, portfolio: 26140 },
  ];

  const maxValue = 28000;
  const minValue = 0;

  const getX = (year: number) => padding.left + (year / 10) * graphWidth;
  const getY = (value: number) => padding.top + graphHeight - ((value - minValue) / (maxValue - minValue)) * graphHeight;

  const investedPath = yearlyData
    .map((d, i) => `${i === 0 ? "M" : "L"} ${getX(d.year)} ${getY(d.invested)}`)
    .join(" ");

  const portfolioPath = yearlyData
    .map((d, i) => `${i === 0 ? "M" : "L"} ${getX(d.year)} ${getY(d.portfolio)}`)
    .join(" ");

  const areaPath = `${portfolioPath} L ${getX(10)} ${getY(0)} L ${getX(0)} ${getY(0)} Z`;

  const yAxisTicks = [0, 5000, 10000, 15000, 20000, 25000];

  const formatCurrency = (value: number) => {
    if (value >= 1000) {
      return `₹${(value / 1000).toFixed(value >= 10000 ? 0 : 1)}K`;
    }
    return `₹${value}`;
  };

  return (
    <section
      ref={sectionRef}
      className="relative overflow-hidden bg-card/30 px-4 py-20 sm:px-6 sm:py-24 md:py-32"
      data-testid="section-performance"
    >
      <div 
        className={`absolute top-0 right-0 w-96 h-96 bg-chart-2/5 rounded-full blur-3xl transition-all duration-1000 ${
          isVisible ? "opacity-100 translate-x-0" : "opacity-0 translate-x-20"
        }`}
      />

      <div className="max-w-4xl mx-auto relative">
        <div className="text-center mb-16">
          <p 
            className={`text-sm uppercase tracking-widest text-muted-foreground mb-4 transition-all duration-700 ${
              isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
          >
            The Power of Compounding
          </p>
          <h2 
            className={`mb-4 text-3xl font-bold transition-all duration-700 delay-100 sm:text-4xl md:text-5xl ${
              isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
            data-testid="text-performance-headline"
          >
            Watch Your Wealth Grow
          </h2>
          <p 
            className={`text-base text-muted-foreground transition-all duration-700 delay-200 sm:text-lg md:text-xl ${
              isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
          >
            ₹100/month SIP over 10 years at 14% XIRR
          </p>
        </div>

        <div 
          className={`relative rounded-2xl border border-card-border bg-card p-4 transition-all duration-700 delay-300 sm:p-6 md:p-8 ${
            isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
          }`}
        >
          <div className="overflow-x-auto pb-2">
            <div className="min-w-[560px]">
              <svg
                viewBox={`0 0 ${chartWidth} ${chartHeight}`}
                className="h-auto w-full"
                preserveAspectRatio="xMidYMid meet"
              >
            <defs>
              <linearGradient id="investedGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="hsl(var(--muted-foreground))" stopOpacity="0.4" />
                <stop offset="100%" stopColor="hsl(var(--muted-foreground))" stopOpacity="0.8" />
              </linearGradient>
              <linearGradient id="portfolioGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="hsl(var(--chart-2))" />
                <stop offset="100%" stopColor="hsl(var(--chart-1))" />
              </linearGradient>
              <linearGradient id="areaGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" stopColor="hsl(var(--chart-2))" stopOpacity="0.3" />
                <stop offset="100%" stopColor="hsl(var(--chart-2))" stopOpacity="0" />
              </linearGradient>
              <filter id="glow">
                <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
                <feMerge>
                  <feMergeNode in="coloredBlur"/>
                  <feMergeNode in="SourceGraphic"/>
                </feMerge>
              </filter>
            </defs>

            {yAxisTicks.map((tick, i) => (
              <g key={tick}>
                <line
                  x1={padding.left}
                  y1={getY(tick)}
                  x2={chartWidth - padding.right}
                  y2={getY(tick)}
                  stroke="hsl(var(--border))"
                  strokeWidth="1"
                  strokeDasharray="4 4"
                  className="transition-opacity duration-500"
                  style={{ 
                    opacity: isVisible ? 0.3 : 0,
                    transitionDelay: `${i * 100}ms`
                  }}
                />
                <text
                  x={padding.left - 10}
                  y={getY(tick) + 4}
                  fill="hsl(var(--muted-foreground))"
                  fontSize="11"
                  textAnchor="end"
                  className="font-sans"
                  style={{ 
                    opacity: isVisible ? 1 : 0,
                    transition: `opacity 0.5s ease ${i * 100}ms`
                  }}
                >
                  {formatCurrency(tick)}
                </text>
              </g>
            ))}

            <line
              x1={padding.left}
              y1={chartHeight - padding.bottom}
              x2={chartWidth - padding.right}
              y2={chartHeight - padding.bottom}
              stroke="hsl(var(--border))"
              strokeWidth="1"
            />

            {[0, 2, 4, 6, 8, 10].map((year) => (
              <text
                key={year}
                x={getX(year)}
                y={chartHeight - padding.bottom + 25}
                fill="hsl(var(--muted-foreground))"
                fontSize="11"
                textAnchor="middle"
                className="font-sans"
              >
                {year === 0 ? "Start" : `Year ${year}`}
              </text>
            ))}

            {animationPhase >= 2 && (
              <path
                d={areaPath}
                fill="url(#areaGradient)"
                className="transition-opacity duration-1000"
                style={{ opacity: animationPhase >= 3 ? 1 : 0 }}
              />
            )}

            <path
              d={investedPath}
              fill="none"
              stroke="url(#investedGradient)"
              strokeWidth="3"
              strokeLinecap="round"
              strokeDasharray="600"
              strokeDashoffset={animationPhase >= 1 ? 0 : 600}
              style={{ transition: "stroke-dashoffset 1.5s ease-out" }}
            />

            <path
              d={portfolioPath}
              fill="none"
              stroke="url(#portfolioGradient)"
              strokeWidth="3"
              strokeLinecap="round"
              strokeDasharray="600"
              strokeDashoffset={animationPhase >= 2 ? 0 : 600}
              style={{ transition: "stroke-dashoffset 1.5s ease-out" }}
              filter={animationPhase >= 3 ? "url(#glow)" : "none"}
            />

            {animationPhase >= 1 && yearlyData.slice(1).map((d, i) => (
              <circle
                key={`inv-${i}`}
                cx={getX(d.year)}
                cy={getY(d.invested)}
                r="4"
                fill="hsl(var(--background))"
                stroke="hsl(var(--muted-foreground))"
                strokeWidth="2"
                className="cursor-pointer transition-all duration-300"
                style={{
                  opacity: animationPhase >= 1 ? 1 : 0,
                  transform: `scale(${animationPhase >= 1 ? 1 : 0})`,
                  transformOrigin: `${getX(d.year)}px ${getY(d.invested)}px`,
                  transition: `all 0.3s ease-out ${i * 0.1}s`,
                }}
                onMouseEnter={() => setHoveredPoint({ 
                  x: getX(d.year), 
                  y: getY(d.invested), 
                  label: "Invested",
                  value: `₹${d.invested.toLocaleString("en-IN")}`
                })}
                onMouseLeave={() => setHoveredPoint(null)}
              />
            ))}

            {animationPhase >= 2 && yearlyData.slice(1).map((d, i) => (
              <circle
                key={`port-${i}`}
                cx={getX(d.year)}
                cy={getY(d.portfolio)}
                r="5"
                fill="hsl(var(--chart-2))"
                className="cursor-pointer"
                style={{
                  opacity: animationPhase >= 2 ? 1 : 0,
                  transform: `scale(${animationPhase >= 2 ? 1 : 0})`,
                  transformOrigin: `${getX(d.year)}px ${getY(d.portfolio)}px`,
                  transition: `all 0.3s ease-out ${i * 0.1}s`,
                }}
                onMouseEnter={() => setHoveredPoint({ 
                  x: getX(d.year), 
                  y: getY(d.portfolio), 
                  label: "Portfolio",
                  value: `₹${d.portfolio.toLocaleString("en-IN")}`
                })}
                onMouseLeave={() => setHoveredPoint(null)}
              />
            ))}

            {hoveredPoint && (
              <g>
                <rect
                  x={hoveredPoint.x - 55}
                  y={hoveredPoint.y - 40}
                  width="110"
                  height="30"
                  rx="6"
                  fill="hsl(var(--popover))"
                  stroke="hsl(var(--border))"
                />
                <text
                  x={hoveredPoint.x}
                  y={hoveredPoint.y - 20}
                  textAnchor="middle"
                  fill="hsl(var(--foreground))"
                  fontSize="12"
                  fontWeight="500"
                  className="font-sans"
                >
                  {hoveredPoint.label}: {hoveredPoint.value}
                </text>
              </g>
            )}

            {animationPhase >= 3 && (
              <g>
                <rect
                  x={getX(10) - 45}
                  y={getY(26140) - 35}
                  width="90"
                  height="28"
                  rx="6"
                  fill="hsl(var(--chart-2))"
                  fillOpacity="0.15"
                  stroke="hsl(var(--chart-2))"
                  strokeOpacity="0.3"
                />
                <text
                  x={getX(10)}
                  y={getY(26140) - 16}
                  textAnchor="middle"
                  fill="hsl(var(--chart-2))"
                  fontSize="13"
                  fontWeight="bold"
                  className="font-sans animate-pulse"
                >
                  +118% gains
                </text>
              </g>
            )}
              </svg>
            </div>
          </div>

          <div className="mt-8 flex flex-wrap items-center justify-center gap-4 sm:gap-8">
            <div 
              className={`flex items-center gap-3 transition-all duration-500 ${
                animationPhase >= 1 ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
              }`}
            >
              <div className="w-4 h-1 rounded-full bg-muted-foreground/70" />
              <span className="text-sm text-muted-foreground">Total Invested: ₹12,000</span>
            </div>
            <div 
              className={`flex items-center gap-3 transition-all duration-500 delay-500 ${
                animationPhase >= 2 ? "opacity-100 translate-x-0" : "opacity-0 translate-x-4"
              }`}
            >
              <div className="w-4 h-1 rounded-full bg-chart-2" />
              <span className="text-sm text-muted-foreground">Portfolio Value: ₹26,140</span>
            </div>
          </div>

          <p 
            className={`text-center text-xs text-muted-foreground/60 mt-6 transition-all duration-500 delay-700 ${
              animationPhase >= 3 ? "opacity-100" : "opacity-0"
            }`}
          >
            Based on 14% XIRR average returns. Past performance does not guarantee future results.
          </p>
        </div>
      </div>
    </section>
  );
}
