import React, { useRef, useState, useEffect } from "react";
import {
  ArrowDown,
  Check,
  BookOpen,
  TrendingUp,
  Grid,
  RefreshCw,
} from "lucide-react";
import ParabolaWidget from "../../../components/lessons/ParabolaWidget";
import DiscriminantWidget from "../../../components/lessons/DiscriminantWidget";
import LinearQuadraticSystemWidget from "../../../components/lessons/LinearQuadraticSystemWidget";
import Quiz from "../../../components/lessons/Quiz";
import { QUADRATIC_EQ_QUIZ_DATA } from "../../../utils/constants";
import { Frac } from "../../../components/Math";

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

const QuadraticEquationsLesson: 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",
    });
  };

  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-violet-100" : "hover:bg-slate-100"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${isActive ? "bg-violet-600 text-white" : isPast ? "bg-violet-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-violet-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="Parabolas & Forms"
            icon={TrendingUp}
          />
          <SectionMarker
            index={1}
            title="Solving & Discriminant"
            icon={RefreshCw}
          />
          <SectionMarker index={2} title="Systems" icon={Grid} />
          <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: Parabolas & Forms */}
        <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">
            Parabolas & Quadratic Forms
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              A quadratic function creates a U-shaped curve called a{" "}
              <strong>parabola</strong>. The SAT uses three different but
              equivalent forms — each form highlights different features.
              Knowing all three lets you pick the most efficient approach for
              each question.
            </p>
          </div>

          {/* Three Forms Card */}
          <div className="bg-violet-50 border border-violet-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-violet-900">
              The Three Quadratic Forms
            </h3>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <div className="flex items-baseline gap-3 mb-2">
                <span className="text-xs font-bold uppercase tracking-wider text-violet-500 bg-violet-100 px-2 py-0.5 rounded">
                  Standard Form
                </span>
              </div>
              <p className="font-mono text-violet-800 font-bold text-xl text-center mb-3">
                y = ax² + bx + c
              </p>
              <ul className="text-slate-600 text-sm space-y-1 list-disc list-inside">
                <li>
                  <strong>a &gt; 0</strong>: parabola opens upward (U-shape);{" "}
                  <strong>a &lt; 0</strong>: opens downward (∩-shape)
                </li>
                <li>
                  <strong>|a| &gt; 1</strong>: narrow parabola;{" "}
                  <strong>|a| &lt; 1</strong>: wide parabola
                </li>
                <li>
                  <strong>c</strong> is the y-intercept (the value of y when x =
                  0)
                </li>
                <li>
                  Vertex x-coordinate: x = <Frac n="−b" d="2a" />
                </li>
                <li>
                  Axis of symmetry: x = <Frac n="−b" d="2a" />
                </li>
              </ul>
              <div className="mt-3 bg-violet-50 rounded-lg p-3 text-sm">
                <p className="font-semibold text-violet-800">Example:</p>
                <p className="text-slate-600">
                  y = 2x² − 8x + 6 → axis of symmetry: x ={" "}
                  <Frac n="−(−8)" d="2 × 2" /> = <Frac n="8" d="4" /> ={" "}
                  <strong>2</strong>
                </p>
              </div>
            </div>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <div className="flex items-baseline gap-3 mb-2">
                <span className="text-xs font-bold uppercase tracking-wider text-violet-500 bg-violet-100 px-2 py-0.5 rounded">
                  Vertex Form
                </span>
              </div>
              <p className="font-mono text-violet-800 font-bold text-xl text-center mb-3">
                y = a(x − h)² + k
              </p>
              <ul className="text-slate-600 text-sm space-y-1 list-disc list-inside">
                <li>Vertex is at (h, k) — read directly from the equation</li>
                <li>
                  Watch the sign: y = a(x − <strong>3</strong>)² + 5 has vertex
                  at (<strong>3</strong>, 5), not (−3, 5)
                </li>
                <li>
                  k is the minimum value (if a &gt; 0) or maximum value (if a
                  &lt; 0) of y
                </li>
                <li>
                  Best form to use when a question asks about the vertex,
                  minimum, or maximum
                </li>
              </ul>
              <div className="mt-3 bg-violet-50 rounded-lg p-3 text-sm">
                <p className="font-semibold text-violet-800">Example:</p>
                <p className="text-slate-600">
                  y = −3(x + 2)² + 7 → vertex at (−2, 7); maximum value is{" "}
                  <strong>7</strong> (since a = −3 &lt; 0)
                </p>
              </div>
            </div>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <div className="flex items-baseline gap-3 mb-2">
                <span className="text-xs font-bold uppercase tracking-wider text-violet-500 bg-violet-100 px-2 py-0.5 rounded">
                  Factored Form
                </span>
              </div>
              <p className="font-mono text-violet-800 font-bold text-xl text-center mb-3">
                y = a(x − r₁)(x − r₂)
              </p>
              <ul className="text-slate-600 text-sm space-y-1 list-disc list-inside">
                <li>x-intercepts (roots/zeros) are at x = r₁ and x = r₂</li>
                <li>Set each factor = 0 to find roots: x − r₁ = 0 → x = r₁</li>
                <li>
                  Axis of symmetry is the midpoint of the roots: x ={" "}
                  <Frac n="r₁ + r₂" d="2" />
                </li>
                <li>
                  Best form to use when a question asks about x-intercepts or
                  roots
                </li>
              </ul>
              <div className="mt-3 bg-violet-50 rounded-lg p-3 text-sm">
                <p className="font-semibold text-violet-800">Example:</p>
                <p className="text-slate-600">
                  y = 2(x − 1)(x − 5) → roots at x = 1 and x = 5; axis of
                  symmetry: x = <Frac n="1 + 5" d="2" /> = <strong>3</strong>
                </p>
              </div>
            </div>
          </div>

          {/* Converting Between Forms */}
          <div className="bg-violet-50 border border-violet-200 rounded-2xl p-6 mb-8 space-y-4">
            <h3 className="text-lg font-bold text-violet-900">
              Converting Between Forms
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white rounded-xl p-4 border border-violet-100">
                <p className="font-bold text-violet-800 mb-2">
                  Standard → Vertex (Completing the Square)
                </p>
                <div className="text-sm text-slate-600 space-y-1 font-mono">
                  <p>y = x² − 6x + 5</p>
                  <p>= (x² − 6x + 9) − 9 + 5</p>
                  <p>= (x − 3)² − 4</p>
                  <p className="text-violet-700 font-bold">Vertex: (3, −4)</p>
                </div>
              </div>
              <div className="bg-white rounded-xl p-4 border border-violet-100">
                <p className="font-bold text-violet-800 mb-2">
                  Standard → Factored
                </p>
                <div className="text-sm text-slate-600 space-y-1 font-mono">
                  <p>y = x² − 6x + 5</p>
                  <p>Find two numbers: × = 5, + = −6</p>
                  <p>Those numbers: −1 and −5</p>
                  <p>= (x − 1)(x − 5)</p>
                  <p className="text-violet-700 font-bold">
                    Roots: x = 1 and x = 5
                  </p>
                </div>
              </div>
            </div>
            <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm">
              <p className="font-bold text-red-800 mb-1">
                Common SAT Trap — Vertex Form Sign
              </p>
              <p className="text-slate-700">
                y = (x + 4)² − 3 looks like h = 4, but it's actually y = (x −
                (−4))² − 3, so the vertex is at (<strong>−4</strong>, −3).
                Always rewrite (x + h) as (x − (−h)) to read the vertex
                correctly.
              </p>
            </div>
          </div>

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

        {/* Section 2: Solving & Discriminant */}
        <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">
            Solving Quadratics & The Discriminant
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              There are four methods to solve a quadratic equation. Choosing the
              right method quickly is an important SAT skill. Before diving in,
              check the <strong>Discriminant</strong> — it tells you instantly
              how many real solutions exist.
            </p>
          </div>

          {/* Discriminant Card */}
          <div className="bg-violet-50 border border-violet-200 rounded-2xl p-6 mb-6 space-y-4">
            <h3 className="text-lg font-bold text-violet-900">
              The Discriminant
            </h3>
            <div className="bg-white rounded-xl p-4 text-center border border-violet-100">
              <p className="text-2xl font-mono font-bold text-violet-800">
                Δ = b² − 4ac
              </p>
              <p className="text-slate-500 text-sm mt-1">
                For ax² + bx + c = 0
              </p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm border-collapse">
                <thead>
                  <tr className="bg-violet-200 text-violet-900">
                    <th className="p-3 rounded-tl-lg font-bold text-left">
                      Discriminant Value
                    </th>
                    <th className="p-3 font-bold text-left">
                      Number of Real Solutions
                    </th>
                    <th className="p-3 rounded-tr-lg font-bold text-left">
                      What it Means Graphically
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="bg-white border-b border-violet-100">
                    <td className="p-3 font-bold text-green-700">Δ &gt; 0</td>
                    <td className="p-3 text-slate-600">
                      <strong>2</strong> distinct real solutions
                    </td>
                    <td className="p-3 text-slate-600">
                      Parabola crosses x-axis at two points
                    </td>
                  </tr>
                  <tr className="bg-violet-50 border-b border-violet-100">
                    <td className="p-3 font-bold text-amber-700">Δ = 0</td>
                    <td className="p-3 text-slate-600">
                      <strong>1</strong> repeated real solution
                    </td>
                    <td className="p-3 text-slate-600">
                      Parabola is tangent to x-axis (vertex on x-axis)
                    </td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-3 font-bold text-red-700">Δ &lt; 0</td>
                    <td className="p-3 text-slate-600">
                      <strong>0</strong> real solutions
                    </td>
                    <td className="p-3 text-slate-600">
                      Parabola does not touch x-axis
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          {/* Four Solving Methods */}
          <div className="bg-violet-50 border border-violet-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-violet-900">
              Four Methods to Solve ax² + bx + c = 0
            </h3>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <p className="font-bold text-violet-800 mb-3">
                Method 1: Factoring (fastest when it works)
              </p>
              <p className="text-slate-600 text-sm mb-3">
                Find two numbers that multiply to <strong>a × c</strong> and add
                to <strong>b</strong>.
              </p>
              <div className="bg-violet-50 rounded-lg p-3 font-mono text-sm space-y-1">
                <p className="text-slate-600">Solve: x² + 5x + 6 = 0</p>
                <p className="text-slate-600">
                  Need two numbers: × = 6, + = 5 → <strong>2 and 3</strong>
                </p>
                <p className="text-slate-600">(x + 2)(x + 3) = 0</p>
                <p className="text-violet-700 font-bold">x = −2 or x = −3</p>
              </div>
            </div>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <p className="font-bold text-violet-800 mb-3">
                Method 2: Square Root Method (when b = 0 or vertex form)
              </p>
              <p className="text-slate-600 text-sm mb-3">
                Isolate the squared term, then take the square root of both
                sides. Remember ±.
              </p>
              <div className="bg-violet-50 rounded-lg p-3 font-mono text-sm space-y-1">
                <p className="text-slate-600">Solve: 2x² − 18 = 0</p>
                <p className="text-slate-600">2x² = 18 → x² = 9</p>
                <p className="text-slate-600">x = ±√9</p>
                <p className="text-violet-700 font-bold">x = 3 or x = −3</p>
              </div>
            </div>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <p className="font-bold text-violet-800 mb-3">
                Method 3: Quadratic Formula (always works)
              </p>
              <div className="bg-violet-50 rounded-lg p-3 text-center mb-3">
                <p className="font-mono text-violet-800 font-bold text-lg">
                  x = <Frac n={<>−b ± √(b² − 4ac)</>} d="2a" />
                </p>
              </div>
              <div className="bg-violet-50 rounded-lg p-3 font-mono text-sm space-y-1">
                <p className="text-slate-600">
                  Solve: 2x² − 3x − 2 = 0 (a=2, b=−3, c=−2)
                </p>
                <p className="text-slate-600">
                  Δ = (−3)² − 4(2)(−2) = 9 + 16 = 25
                </p>
                <p className="text-slate-600">
                  x = <Frac n="3 ± √25" d="4" /> = <Frac n="3 ± 5" d="4" />
                </p>
                <p className="text-violet-700 font-bold">x = 2 or x = −½</p>
              </div>
            </div>

            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <p className="font-bold text-violet-800 mb-3">
                Method 4: Completing the Square
              </p>
              <p className="text-slate-600 text-sm mb-3">
                Rewrite into vertex form, then solve. Most useful when the SAT
                asks for vertex form or when coefficients are simple.
              </p>
              <div className="bg-violet-50 rounded-lg p-3 font-mono text-sm space-y-1">
                <p className="text-slate-600">Solve: x² + 6x + 5 = 0</p>
                <p className="text-slate-600">x² + 6x = −5</p>
                <p className="text-slate-600">
                  x² + 6x + 9 = −5 + 9 (add (<Frac n="6" d="2" />
                  )² = 9 to both sides)
                </p>
                <p className="text-slate-600">(x + 3)² = 4</p>
                <p className="text-slate-600">x + 3 = ±2</p>
                <p className="text-violet-700 font-bold">x = −1 or x = −5</p>
              </div>
            </div>
          </div>

          {/* SAT Strategy */}
          <div className="bg-amber-50 border border-amber-200 rounded-2xl p-6 mb-8">
            <h3 className="text-lg font-bold text-amber-900 mb-3">
              SAT Strategy: Which Method to Use?
            </h3>
            <div className="space-y-2 text-sm text-slate-700">
              <div className="flex gap-3 items-start">
                <span className="font-bold text-violet-700 shrink-0">1.</span>
                <p>
                  If the equation factors nicely (integer roots likely) →{" "}
                  <strong>Factor</strong> first. It's fastest.
                </p>
              </div>
              <div className="flex gap-3 items-start">
                <span className="font-bold text-violet-700 shrink-0">2.</span>
                <p>
                  If the middle term is missing (bx = 0) or it's already in
                  vertex form → <strong>Square Root Method</strong>.
                </p>
              </div>
              <div className="flex gap-3 items-start">
                <span className="font-bold text-violet-700 shrink-0">3.</span>
                <p>
                  If you can't factor quickly or need exact answers →{" "}
                  <strong>Quadratic Formula</strong>.
                </p>
              </div>
              <div className="flex gap-3 items-start">
                <span className="font-bold text-violet-700 shrink-0">4.</span>
                <p>
                  If the question asks to "rewrite in vertex form" or "find the
                  vertex" → <strong>Complete the Square</strong>.
                </p>
              </div>
            </div>
          </div>

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

        {/* Section 3: Systems */}
        <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">
            Linear-Quadratic Systems
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              When a line intersects a parabola, the system can have 0, 1, or 2
              solutions. The key strategy is to substitute the linear equation
              into the quadratic, rearrange everything to one side to form a new
              quadratic, then use the discriminant to determine the number of
              intersections.
            </p>
          </div>

          <div className="bg-violet-50 border border-violet-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-violet-900">
              Strategy: 4-Step Process
            </h3>

            <div className="space-y-3">
              {[
                {
                  step: "1",
                  title: "Write out the system",
                  body: "You have a linear equation (y = mx + b) and a quadratic (y = ax² + bx + c). Make sure both are in y = form.",
                },
                {
                  step: "2",
                  title: "Set the right sides equal",
                  body: "Since both equal y, set them equal to each other: mx + b = ax² + bx + c.",
                },
                {
                  step: "3",
                  title: "Rearrange to zero",
                  body: "Move everything to one side: 0 = ax² + (b−m)x + (c−b). You now have a new quadratic equation.",
                },
                {
                  step: "4",
                  title: "Use the Discriminant on the new quadratic",
                  body: "Δ > 0: line crosses parabola at 2 points. Δ = 0: line is tangent (1 point). Δ < 0: line misses parabola (0 points).",
                },
              ].map((item) => (
                <div
                  key={item.step}
                  className="flex gap-4 bg-white rounded-xl p-4 border border-violet-100"
                >
                  <div className="w-8 h-8 bg-violet-600 text-white rounded-full flex items-center justify-center font-bold shrink-0">
                    {item.step}
                  </div>
                  <div>
                    <p className="font-bold text-slate-800 mb-1">
                      {item.title}
                    </p>
                    <p className="text-slate-600 text-sm">{item.body}</p>
                  </div>
                </div>
              ))}
            </div>

            <div className="bg-violet-100 rounded-xl p-5">
              <p className="font-bold text-violet-900 mb-2">Worked Example</p>
              <p className="text-sm text-slate-700 mb-3">
                Find all intersections of y = 2x + 1 and y = x² − 2x + 3.
              </p>
              <div className="font-mono text-sm space-y-1 text-slate-600">
                <p>Set equal: 2x + 1 = x² − 2x + 3</p>
                <p>Rearrange: 0 = x² − 4x + 2</p>
                <p>Discriminant: Δ = (−4)² − 4(1)(2) = 16 − 8 = 8</p>
                <p className="text-violet-700 font-bold">
                  Δ &gt; 0 → 2 intersection points
                </p>
                <p>
                  x = <Frac n="4 ± √8" d="2" /> = 2 ± √2
                </p>
              </div>
            </div>

            <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm">
              <p className="font-bold text-red-800 mb-1">
                Key Distinction: Tangent vs. Intersects
              </p>
              <p className="text-slate-700">
                When the SAT says the line is <em>tangent</em> to the parabola,
                that means exactly 1 intersection → set Δ = 0 and solve for the
                unknown constant.
              </p>
            </div>
          </div>

          <LinearQuadraticSystemWidget />

          <button
            onClick={() => scrollToSection(3)}
            className="mt-12 group flex items-center text-violet-600 font-bold hover:text-violet-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: Quiz */}
        <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>
          {QUADRATIC_EQ_QUIZ_DATA.map((quiz, idx) => (
            <div key={quiz.id} className="mb-12">
              <Quiz data={quiz} />
            </div>
          ))}
          <div className="p-8 bg-violet-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-violet-900 font-bold rounded-full hover:bg-violet-50 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default QuadraticEquationsLesson;
