import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, Target, Calculator } from "lucide-react";
import { Frac } from "../../../components/Math";
import UnitCircleWidget from "../../../components/lessons/UnitCircleWidget";
import Quiz from "../../../components/lessons/Quiz";
import { TRIG_QUIZ_DATA } from "../../../utils/constants";

// --- Interactive Trig Ratios Component (Inline for simplicity or could be separate) ---
const InteractiveTrigRatiosWidget = () => {
  const [angle, setAngle] = useState(30);
  const radius = 200;
  const cx = 50,
    cy = 250; // Bottom-left corner

  // Calculate triangle vertex
  const rad = (angle * Math.PI) / 180;
  const x = radius * Math.cos(rad);
  const y = radius * Math.sin(rad);
  const px = cx + x;
  const py = cy - y;

  // Interaction
  const handleDrag = (e: React.MouseEvent) => {
    const rect = (e.target as Element).closest("svg")?.getBoundingClientRect();
    if (!rect) return;
    const mx = e.clientX - rect.left;
    const my = e.clientY - rect.top;
    const dx = mx - cx;
    const dy = cy - my;
    let deg = (Math.atan2(dy, dx) * 180) / Math.PI;
    deg = Math.max(10, Math.min(80, deg)); // Constrain angle
    setAngle(deg);
  };

  const isDragging = useRef(false);

  return (
    <div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
      <div className="flex flex-col md:flex-row gap-8 items-center">
        <svg
          width="300"
          height="280"
          className="select-none cursor-pointer"
          onMouseDown={() => (isDragging.current = true)}
          onMouseMove={(e) => {
            if (isDragging.current) handleDrag(e);
          }}
          onMouseUp={() => (isDragging.current = false)}
          onMouseLeave={() => (isDragging.current = false)}
        >
          {/* Axes/Grid context */}
          <line
            x1={cx}
            y1={cy}
            x2={cx + 250}
            y2={cy}
            stroke="#cbd5e1"
            strokeWidth="2"
          />
          {/* Triangle */}
          <path
            d={`M ${cx} ${cy} L ${px} ${cy} L ${px} ${py} Z`}
            fill="rgba(224, 242, 254, 0.5)"
            stroke="none"
          />
          <line
            x1={cx}
            y1={cy}
            x2={px}
            y2={py}
            stroke="#0f172a"
            strokeWidth="2"
          />{" "}
          {/* Hypotenuse */}
          <line
            x1={cx}
            y1={cy}
            x2={px}
            y2={cy}
            stroke="#0f172a"
            strokeWidth="2"
          />{" "}
          {/* Adj */}
          <line
            x1={px}
            y1={cy}
            x2={px}
            y2={py}
            stroke="#0f172a"
            strokeWidth="2"
          />{" "}
          {/* Opp */}
          {/* Angle Arc */}
          <path
            d={`M ${cx + 40} ${cy} A 40 40 0 0 0 ${cx + 40 * Math.cos(rad)} ${cy - 40 * Math.sin(rad)}`}
            fill="none"
            stroke="#0ea5e9"
            strokeWidth="2"
          />
          <text x={cx + 50} y={cy - 10} className="font-bold fill-sky-600">
            {Math.round(angle)}°
          </text>
          {/* Labels */}
          <text x={px + 10} y={cy - y / 2} className="font-bold fill-rose-500">
            Opposite
          </text>
          <text
            x={cx + x / 2}
            y={cy + 20}
            className="font-bold fill-indigo-500"
          >
            Adjacent
          </text>
          <text
            x={cx + x / 2 - 20}
            y={cy - y / 2 - 10}
            className="font-bold fill-slate-500"
          >
            Hypotenuse (r)
          </text>
          {/* Drag Handle */}
          <circle
            cx={px}
            cy={py}
            r={8}
            fill="#0ea5e9"
            stroke="white"
            strokeWidth="2"
            className="cursor-grab hover:scale-110 transition-transform"
          />
          {/* Right Angle */}
          <rect
            x={px - 20}
            y={cy - 20}
            width="20"
            height="20"
            fill="none"
            stroke="#94a3b8"
          />
        </svg>

        <div className="flex-1 space-y-4 font-mono">
          <div className="p-3 bg-rose-50 border border-rose-100 rounded-lg">
            <div className="text-xs font-bold text-rose-800 uppercase">
              Sine (Opp/Hyp)
            </div>
            <div className="text-xl font-bold text-rose-900">
              {Math.sin(rad).toFixed(3)}
            </div>
          </div>
          <div className="p-3 bg-indigo-50 border border-indigo-100 rounded-lg">
            <div className="text-xs font-bold text-indigo-800 uppercase">
              Cosine (Adj/Hyp)
            </div>
            <div className="text-xl font-bold text-indigo-900">
              {Math.cos(rad).toFixed(3)}
            </div>
          </div>
          <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg">
            <div className="text-xs font-bold text-slate-800 uppercase">
              Tangent (Opp/Adj)
            </div>
            <div className="text-xl font-bold text-slate-900">
              {Math.tan(rad).toFixed(3)}
            </div>
          </div>
          <p className="text-xs text-slate-400 mt-2">
            Drag the blue vertex to change θ!
          </p>
        </div>
      </div>
    </div>
  );
};

// --- Interactive Special Triangles Component ---
const InteractiveSpecialTrianglesWidget = () => {
  const [scale, setScale] = useState(100);

  return (
    <div className="space-y-8">
      <div className="flex items-center gap-4 bg-slate-100 p-4 rounded-lg">
        <span className="font-bold text-slate-600">Scale (x):</span>
        <input
          type="range"
          min="50"
          max="150"
          value={scale}
          onChange={(e) => setScale(parseInt(e.target.value))}
          className="flex-1 h-2 bg-slate-300 rounded-lg appearance-none cursor-pointer accent-sky-600"
        />
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {/* 45-45-90 */}
        <div className="bg-white p-6 rounded-xl border border-slate-200 text-center flex flex-col items-center">
          <h4 className="font-bold text-xl mb-4 text-slate-800">
            45-45-90 Triangle
          </h4>
          <div className="h-64 flex items-end justify-center pb-4">
            <svg width="200" height="200" className="overflow-visible">
              <path
                d={`M 0 200 L ${scale} 200 L ${scale} ${200 - scale} Z`}
                transform="translate(20, -20)"
                fill="rgba(14, 165, 233, 0.1)"
                stroke="#0ea5e9"
                strokeWidth="2"
              />
              {/* Labels */}
              <g transform="translate(20, -20)">
                <text
                  x={scale / 2}
                  y={220}
                  textAnchor="middle"
                  className="font-bold fill-slate-700"
                >
                  x = {Math.round(scale / 2)}
                </text>
                <text
                  x={scale + 10}
                  y={200 - scale / 2}
                  className="font-bold fill-slate-700"
                >
                  x = {Math.round(scale / 2)}
                </text>
                <text
                  x={scale / 2 - 10}
                  y={200 - scale / 2}
                  textAnchor="end"
                  className="font-bold fill-sky-600"
                >
                  x√2 ≈ {Math.round((scale / 2) * 1.414)}
                </text>
                <text x={20} y={190} className="text-xs fill-slate-400">
                  45°
                </text>
                <text
                  x={scale - 10}
                  y={200 - scale + 20}
                  className="text-xs fill-slate-400"
                >
                  45°
                </text>
              </g>
            </svg>
          </div>
          <p className="text-sm text-slate-500 font-medium">
            Sides: 1 : 1 : √2
          </p>
        </div>

        {/* 30-60-90 */}
        <div className="bg-white p-6 rounded-xl border border-slate-200 text-center flex flex-col items-center">
          <h4 className="font-bold text-xl mb-4 text-slate-800">
            30-60-90 Triangle
          </h4>
          <div className="h-64 flex items-end justify-center pb-4">
            <svg width="200" height="200" className="overflow-visible">
              {/* Base is x, Height is x√3 */}
              <path
                d={`M 0 200 L ${scale} 200 L ${scale} ${200 - scale * 1.732} Z`}
                transform="translate(20, 0)"
                fill="rgba(14, 165, 233, 0.1)"
                stroke="#0ea5e9"
                strokeWidth="2"
              />
              <g transform="translate(20, 0)">
                <text
                  x={scale / 2}
                  y={220}
                  textAnchor="middle"
                  className="font-bold fill-slate-700"
                >
                  x = {Math.round(scale / 2)}
                </text>
                <text
                  x={scale + 10}
                  y={200 - (scale * 1.732) / 2}
                  className="font-bold fill-slate-700"
                >
                  x√3 ≈ {Math.round((scale / 2) * 1.732)}
                </text>
                <text
                  x={scale / 2 - 10}
                  y={200 - (scale * 1.732) / 2}
                  textAnchor="end"
                  className="font-bold fill-sky-600"
                >
                  2x = {scale}
                </text>
                <text
                  x={scale - 20}
                  y={200 - scale * 1.732 + 30}
                  className="text-xs fill-slate-400"
                >
                  30°
                </text>
                <text x={20} y={190} className="text-xs fill-slate-400">
                  60°
                </text>
              </g>
            </svg>
          </div>
          <p className="text-sm text-slate-500 font-medium">
            Sides: 1 : √3 : 2
          </p>
        </div>
      </div>
    </div>
  );
};

interface LessonProps {
  onFinish?: () => void;
}

const TrigLesson: React.FC<LessonProps> = ({ onFinish }) => {
  const [activeSection, setActiveSection] = useState(0);
  const sectionsRef = useRef<(HTMLElement | null)[]>([]);

  const scrollToSection = (index: number) => {
    setActiveSection(index);
    sectionsRef.current[index]?.scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  };

  // Scroll Spy Effect
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const index = sectionsRef.current.indexOf(
              entry.target as HTMLElement,
            );
            if (index !== -1) {
              setActiveSection(index);
            }
          }
        });
      },
      {
        rootMargin: "-20% 0px -60% 0px",
      },
    );

    sectionsRef.current.forEach((section) => {
      if (section) observer.observe(section);
    });

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

  const SectionMarker = ({
    index,
    title,
    icon: Icon,
  }: {
    index: number;
    title: string;
    icon: any;
  }) => {
    const isActive = activeSection === index;
    const isPast = activeSection > index;
    return (
      <button
        onClick={() => scrollToSection(index)}
        className={`flex items-center gap-3 p-3 w-full rounded-lg transition-all ${
          isActive
            ? "bg-white shadow-md border border-sky-100"
            : "hover:bg-slate-100"
        }`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${
            isActive
              ? "bg-sky-600 text-white"
              : isPast
                ? "bg-sky-400 text-white"
                : "bg-slate-200 text-slate-500"
          }`}
        >
          {isPast ? (
            <Check className="w-4 h-4" />
          ) : (
            <Icon className="w-4 h-4" />
          )}
        </div>
        <div className="text-left">
          <p
            className={`text-sm font-bold ${isActive ? "text-sky-900" : "text-slate-600"}`}
          >
            {title}
          </p>
        </div>
      </button>
    );
  };

  return (
    <div className="flex flex-col lg:flex-row min-h-screen">
      <aside className="w-full lg:w-64 lg:fixed lg:top-20 lg:bottom-0 lg:overflow-y-auto p-4 border-r border-slate-200 bg-slate-50 lg:bg-transparent z-0 hidden lg:block">
        <nav className="space-y-2">
          <SectionMarker
            index={0}
            title="Unit Circle & Radians"
            icon={Target}
          />
          <SectionMarker index={1} title="Trig Ratios" icon={Calculator} />
          <SectionMarker index={2} title="Special Triangles" icon={BookOpen} />
          <SectionMarker index={3} title="Practice" icon={BookOpen} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 p-6 md:p-12 max-w-4xl mx-auto">
        {/* Section 1 */}
        <section
          ref={(el) => {
            sectionsRef.current[0] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24 pt-20 lg:pt-0"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-6">
            Radians & The Unit Circle
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              The unit circle connects geometry and trigonometry. In this
              circle, the radius is always <strong>1</strong>. This means the
              coordinates of any point on the circle are simply{" "}
              <strong>(cos θ, sin θ)</strong>.
            </p>
            <p className="mt-4">
              <strong>Radians</strong> are another way to measure angles. A full
              circle (360°) is <strong>2π radians</strong>.
              <br />
              Use the interactive tool below to explore how angles, radians, and
              coordinates relate.
              <br />
              <span className="text-sm bg-sky-100 text-sky-800 px-2 py-1 rounded font-bold">
                Try dragging the point or clicking the special angle buttons!
              </span>
            </p>
          </div>

          <UnitCircleWidget />

          <button
            onClick={() => scrollToSection(1)}
            className="mt-12 group flex items-center text-sky-600 font-bold hover:text-sky-800 transition-colors"
          >
            Next: SOH CAH TOA{" "}
            <ArrowDown className="ml-2 w-5 h-5 group-hover:translate-y-1 transition-transform" />
          </button>
        </section>

        {/* Section 2 */}
        <section
          ref={(el) => {
            sectionsRef.current[1] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-6">
            Trigonometric Ratios
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              In a right triangle, the three main trig ratios connect each acute
              angle to a pair of sides. Memorize <strong>SOH CAH TOA</strong> —
              it solves the majority of SAT trig problems.
            </p>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
              <div className="bg-rose-50 border border-rose-200 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-rose-700 mb-1">SOH</div>
                <div className="font-bold text-rose-900">
                  sin θ = <Frac n="Opp" d="Hyp" />
                </div>
                <div className="text-xs text-slate-500 mt-2">
                  Opposite over Hypotenuse
                </div>
              </div>
              <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-indigo-700 mb-1">
                  CAH
                </div>
                <div className="font-bold text-indigo-900">
                  cos θ = <Frac n="Adj" d="Hyp" />
                </div>
                <div className="text-xs text-slate-500 mt-2">
                  Adjacent over Hypotenuse
                </div>
              </div>
              <div className="bg-slate-100 border border-slate-300 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-slate-700 mb-1">
                  TOA
                </div>
                <div className="font-bold text-slate-900">
                  tan θ = <Frac n="Opp" d="Adj" />
                </div>
                <div className="text-xs text-slate-500 mt-2">
                  Opposite over Adjacent
                </div>
              </div>
            </div>

            {/* Worked Example */}
            <div className="mt-4 bg-sky-50 border border-sky-200 rounded-xl p-5 text-sm">
              <p className="font-bold text-sky-900 mb-2">
                Worked Example — Using SOH CAH TOA
              </p>
              <p className="text-slate-700 mb-2">
                In a right triangle, the side opposite to angle θ is 5, and the
                hypotenuse is 13. Find sin θ, cos θ, and tan θ.
              </p>
              <div className="bg-white rounded-lg p-3 font-mono text-xs text-slate-700 space-y-1">
                <p>
                  First find the adjacent side: a² + 5² = 13² → a² = 169 − 25 =
                  144 → a = 12
                </p>
                <p className="text-rose-700 font-bold">
                  sin θ = <Frac n="5" d="13" /> ≈ 0.385
                </p>
                <p className="text-indigo-700 font-bold">
                  cos θ = <Frac n="12" d="13" /> ≈ 0.923
                </p>
                <p className="text-slate-700 font-bold">
                  tan θ = <Frac n="5" d="12" /> ≈ 0.417
                </p>
              </div>
            </div>

            <div className="mt-4 bg-sky-50 border-l-4 border-sky-500 p-4 rounded-r-lg text-sm">
              <strong className="text-sky-900">
                Co-function Identity (SAT favourite!):
              </strong>
              <span className="text-slate-700">
                {" "}
                sin(θ) = cos(90° − θ). So sin(30°) = cos(60°). If an angle and
                its complement appear in the same triangle, their sin and cos
                are swapped. This is tested as: "sin(x°) = cos(y°), and x + y =
                90. Find y if x = 32."
              </span>
            </div>
            <p className="mt-4 text-sm text-slate-500">
              Drag the blue point below to see how the three values change with
              the angle.
            </p>
          </div>

          <InteractiveTrigRatiosWidget />

          <button
            onClick={() => scrollToSection(2)}
            className="mt-12 group flex items-center text-sky-600 font-bold hover:text-sky-800 transition-colors"
          >
            Next: Special Triangles{" "}
            <ArrowDown className="ml-2 w-5 h-5 group-hover:translate-y-1 transition-transform" />
          </button>
        </section>

        {/* Section 3 */}
        <section
          ref={(el) => {
            sectionsRef.current[2] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-6">
            Special Right Triangles
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              These two triangle types appear on every SAT. You must know their
              exact side ratios — no calculator needed.
            </p>
            <div className="grid md:grid-cols-2 gap-4 mt-4">
              <div className="bg-sky-50 border border-sky-200 rounded-xl p-5">
                <p className="font-bold text-sky-900 mb-2">45-45-90 Triangle</p>
                <div className="font-mono text-center bg-white py-2 rounded text-sky-700 font-bold mb-2">
                  1 : 1 : √2
                </div>
                <p className="text-sm text-slate-700">
                  If leg = x, then hypotenuse = x√2.
                </p>
                <p className="text-xs text-slate-500 mt-1">
                  Isosceles right triangle. Appears in squares cut diagonally.
                </p>
              </div>
              <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-5">
                <p className="font-bold text-indigo-900 mb-2">
                  30-60-90 Triangle
                </p>
                <div className="font-mono text-center bg-white py-2 rounded text-indigo-700 font-bold mb-2">
                  1 : √3 : 2
                </div>
                <p className="text-sm text-slate-700">
                  Short leg = x, long leg = x√3, hypotenuse = 2x.
                </p>
                <p className="text-xs text-slate-500 mt-1">
                  Half an equilateral triangle. The 2 is always the hypotenuse.
                </p>
              </div>
            </div>
            <div className="overflow-x-auto mt-4 rounded-xl border border-slate-200">
              <table className="w-full text-sm border-collapse text-center">
                <thead>
                  <tr className="bg-slate-800 text-white">
                    <th className="p-2">Angle</th>
                    <th className="p-2">sin θ</th>
                    <th className="p-2">cos θ</th>
                    <th className="p-2">tan θ</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  <tr className="bg-white">
                    <td className="p-2 font-bold">30°</td>
                    <td className="p-2 text-center">
                      <Frac n="1" d="2" />
                    </td>
                    <td className="p-2 text-center">
                      <Frac n="√3" d="2" />
                    </td>
                    <td className="p-2 text-center">
                      <Frac n="√3" d="3" />
                    </td>
                  </tr>
                  <tr className="bg-slate-50">
                    <td className="p-2 font-bold">45°</td>
                    <td className="p-2 text-center">
                      <Frac n="√2" d="2" />
                    </td>
                    <td className="p-2 text-center">
                      <Frac n="√2" d="2" />
                    </td>
                    <td className="p-2 font-mono text-center">1</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-2 font-bold">60°</td>
                    <td className="p-2 text-center">
                      <Frac n="√3" d="2" />
                    </td>
                    <td className="p-2 text-center">
                      <Frac n="1" d="2" />
                    </td>
                    <td className="p-2 font-mono text-center">√3</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div className="mt-3 bg-sky-50 border border-sky-200 rounded-xl p-4 text-sm">
              <p className="font-bold text-sky-900 mb-1">
                Memory Trick for the Table
              </p>
              <p className="text-slate-700">
                For sin: 30° → ½, 45° → √2÷2, 60° → √3÷2. Notice sin{" "}
                <em>increases</em> as the angle increases (from ½ to 1). For
                cos, it's the reverse — cos 30° = √3÷2, cos 60° = ½. And tan 45°
                = 1 because opposite = adjacent in a 45-45-90 triangle.
              </p>
            </div>
            <p className="mt-3 text-sm text-slate-500">
              Use the slider below to scale the triangles and confirm the side
              proportions hold.
            </p>
          </div>

          <InteractiveSpecialTrianglesWidget />

          <button
            onClick={() => scrollToSection(3)}
            className="mt-12 group flex items-center text-sky-600 font-bold hover:text-sky-800 transition-colors"
          >
            Next: Practice Quiz{" "}
            <ArrowDown className="ml-2 w-5 h-5 group-hover:translate-y-1 transition-transform" />
          </button>
        </section>

        {/* Section 4 */}
        <section
          ref={(el) => {
            sectionsRef.current[3] = el;
          }}
          className="min-h-screen flex flex-col justify-center"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-8">
            Practice Time
          </h2>
          {TRIG_QUIZ_DATA.map((quiz, idx) => (
            <div key={quiz.id} className="mb-12">
              <Quiz data={quiz} />
            </div>
          ))}
          <div className="p-8 bg-sky-900 rounded-2xl text-white text-center mt-12">
            <h3 className="text-2xl font-bold mb-4">Topic Mastered!</h3>
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-white text-sky-900 font-bold rounded-full hover:bg-sky-50 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default TrigLesson;
