import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, TrendingUp, Grid } from "lucide-react";
import PolynomialBehaviorWidget from "../../../components/lessons/PolynomialBehaviorWidget";
import MultiplicityWidget from "../../../components/lessons/MultiplicityWidget";
import Quiz from "../../../components/lessons/Quiz";
import { ADV_POLYNOMIAL_QUIZ } from "../../../utils/constants";

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

const PolynomialFunctionsLesson: 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="End Behavior" icon={TrendingUp} />
          <SectionMarker index={1} title="Zeros & Multiplicity" icon={Grid} />
          <SectionMarker index={2} 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: End Behavior */}
        <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">
            End Behavior of Polynomials
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              As x grows very large (→ +∞) or very negative (→ −∞), a
              polynomial's value is dominated by its{" "}
              <strong>leading term</strong> — the term with the highest power.
              To predict end behavior, you only need to look at two things: the{" "}
              <strong>degree</strong> (even or odd) and the{" "}
              <strong>sign of the leading coefficient</strong>.
            </p>
          </div>

          {/* End Behavior Table */}
          <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">
              The Four End Behavior Rules
            </h3>
            <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">
                      Degree
                    </th>
                    <th className="p-3 font-bold text-left">
                      Leading Coefficient
                    </th>
                    <th className="p-3 font-bold text-left">As x → −∞</th>
                    <th className="p-3 rounded-tr-lg font-bold text-left">
                      As x → +∞
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr className="bg-white border-b border-violet-100">
                    <td className="p-3 font-bold text-violet-700">
                      Even (2, 4, 6…)
                    </td>
                    <td className="p-3 text-green-700 font-semibold">
                      Positive (+)
                    </td>
                    <td className="p-3 text-slate-600">y → +∞ (rises left)</td>
                    <td className="p-3 text-slate-600">y → +∞ (rises right)</td>
                  </tr>
                  <tr className="bg-violet-50 border-b border-violet-100">
                    <td className="p-3 font-bold text-violet-700">
                      Even (2, 4, 6…)
                    </td>
                    <td className="p-3 text-red-700 font-semibold">
                      Negative (−)
                    </td>
                    <td className="p-3 text-slate-600">y → −∞ (falls left)</td>
                    <td className="p-3 text-slate-600">y → −∞ (falls right)</td>
                  </tr>
                  <tr className="bg-white border-b border-violet-100">
                    <td className="p-3 font-bold text-violet-700">
                      Odd (1, 3, 5…)
                    </td>
                    <td className="p-3 text-green-700 font-semibold">
                      Positive (+)
                    </td>
                    <td className="p-3 text-slate-600">y → −∞ (falls left)</td>
                    <td className="p-3 text-slate-600">y → +∞ (rises right)</td>
                  </tr>
                  <tr className="bg-violet-50">
                    <td className="p-3 font-bold text-violet-700">
                      Odd (1, 3, 5…)
                    </td>
                    <td className="p-3 text-red-700 font-semibold">
                      Negative (−)
                    </td>
                    <td className="p-3 text-slate-600">y → +∞ (rises left)</td>
                    <td className="p-3 text-slate-600">y → −∞ (falls right)</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <div className="bg-violet-100 rounded-xl p-4 text-sm">
              <p className="font-bold text-violet-900 mb-2">
                Memory Trick: "Even = Same Ends, Odd = Opposite Ends"
              </p>
              <p className="text-slate-700">
                Even degree → both ends go the same direction (both up or both
                down). Odd degree → ends go in opposite directions (one up, one
                down). The sign of the leading coefficient tells you which
                direction is "up".
              </p>
            </div>

            <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">Example 1</p>
                <p className="font-mono text-sm text-slate-700 mb-2">
                  f(x) = 3x⁴ − 2x² + 1
                </p>
                <ul className="text-slate-600 text-sm space-y-1 list-disc list-inside">
                  <li>Degree = 4 (even)</li>
                  <li>Leading coefficient = 3 (positive)</li>
                  <li>Both ends rise → ↑ ↑</li>
                </ul>
              </div>
              <div className="bg-white rounded-xl p-4 border border-violet-100">
                <p className="font-bold text-violet-800 mb-2">Example 2</p>
                <p className="font-mono text-sm text-slate-700 mb-2">
                  g(x) = −2x⁵ + x³ − 4x
                </p>
                <ul className="text-slate-600 text-sm space-y-1 list-disc list-inside">
                  <li>Degree = 5 (odd)</li>
                  <li>Leading coefficient = −2 (negative)</li>
                  <li>Rises left, falls right → ↑ ↓</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Degree and Number of Turns */}
          <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">
              Degree, Turns & Intercepts
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-white rounded-xl p-4 border border-violet-100 text-center">
                <p className="font-bold text-violet-800 mb-1">Maximum Turns</p>
                <p className="text-2xl font-mono font-bold text-violet-600">
                  n − 1
                </p>
                <p className="text-slate-500 text-xs mt-1">
                  A degree-n polynomial can change direction at most n − 1
                  times.
                </p>
              </div>
              <div className="bg-white rounded-xl p-4 border border-violet-100 text-center">
                <p className="font-bold text-violet-800 mb-1">
                  Max x-Intercepts
                </p>
                <p className="text-2xl font-mono font-bold text-violet-600">
                  n
                </p>
                <p className="text-slate-500 text-xs mt-1">
                  A degree-n polynomial can cross the x-axis at most n times.
                </p>
              </div>
              <div className="bg-white rounded-xl p-4 border border-violet-100 text-center">
                <p className="font-bold text-violet-800 mb-1">y-Intercept</p>
                <p className="text-2xl font-mono font-bold text-violet-600">
                  f(0)
                </p>
                <p className="text-slate-500 text-xs mt-1">
                  Plug x = 0 — only the constant term survives.
                </p>
              </div>
            </div>
          </div>

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

        {/* Section 2: Zeros & Multiplicity */}
        <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">
            Zeros, Roots & Multiplicity
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              The <strong>zeros</strong> (or roots) of a polynomial are the
              x-values where f(x) = 0. In factored form, each factor (x − r)
              contributes a root at x = r. The <strong>multiplicity</strong> of
              a root tells us how many times that factor is repeated, which
              determines the graph's behavior at that x-intercept.
            </p>
          </div>

          {/* Multiplicity Rules */}
          <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">
              How Multiplicity Affects the Graph
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white rounded-xl p-5 border border-violet-100">
                <div className="text-center mb-3">
                  <span className="inline-block bg-blue-100 text-blue-800 font-bold px-3 py-1 rounded-full text-sm">
                    Odd Multiplicity (1, 3, 5…)
                  </span>
                </div>
                <p className="text-slate-600 text-sm mb-2">
                  The graph <strong>crosses through</strong> the x-axis at that
                  root. It passes from one side to the other.
                </p>
                <div className="bg-blue-50 rounded-lg p-3 font-mono text-sm">
                  <p className="text-slate-600">f(x) = (x − 2)¹(x + 1)³</p>
                  <p className="text-blue-700 font-bold mt-1">
                    Both x = 2 and x = −1 are crossings
                  </p>
                </div>
              </div>
              <div className="bg-white rounded-xl p-5 border border-violet-100">
                <div className="text-center mb-3">
                  <span className="inline-block bg-green-100 text-green-800 font-bold px-3 py-1 rounded-full text-sm">
                    Even Multiplicity (2, 4, 6…)
                  </span>
                </div>
                <p className="text-slate-600 text-sm mb-2">
                  The graph <strong>touches and bounces off</strong> the x-axis
                  at that root. It stays on the same side.
                </p>
                <div className="bg-green-50 rounded-lg p-3 font-mono text-sm">
                  <p className="text-slate-600">f(x) = (x − 3)²(x + 2)⁴</p>
                  <p className="text-green-700 font-bold mt-1">
                    Both x = 3 and x = −2 are bounces
                  </p>
                </div>
              </div>
            </div>

            {/* Worked Example */}
            <div className="bg-white rounded-xl p-5 border border-violet-100">
              <p className="font-bold text-violet-800 mb-3">
                Complete Analysis — Worked Example
              </p>
              <p className="font-mono text-slate-700 text-sm mb-3">
                f(x) = −2(x + 3)(x − 1)²(x − 4)
              </p>
              <div className="overflow-x-auto">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="bg-violet-100 text-violet-900">
                      <th className="p-2 text-left font-bold">Feature</th>
                      <th className="p-2 text-left font-bold">
                        Value/Description
                      </th>
                    </tr>
                  </thead>
                  <tbody className="text-slate-600">
                    <tr className="border-b border-violet-50">
                      <td className="p-2 font-semibold">Degree</td>
                      <td className="p-2">1 + 2 + 1 = 4 (even)</td>
                    </tr>
                    <tr className="border-b border-violet-50 bg-violet-50">
                      <td className="p-2 font-semibold">Leading coefficient</td>
                      <td className="p-2">−2 (negative)</td>
                    </tr>
                    <tr className="border-b border-violet-50">
                      <td className="p-2 font-semibold">End behavior</td>
                      <td className="p-2">
                        Both ends fall (even degree, negative leading
                        coefficient)
                      </td>
                    </tr>
                    <tr className="border-b border-violet-50 bg-violet-50">
                      <td className="p-2 font-semibold">Zero at x = −3</td>
                      <td className="p-2">
                        Multiplicity 1 (odd) → graph <strong>crosses</strong>
                      </td>
                    </tr>
                    <tr className="border-b border-violet-50">
                      <td className="p-2 font-semibold">Zero at x = 1</td>
                      <td className="p-2">
                        Multiplicity 2 (even) → graph <strong>bounces</strong>
                      </td>
                    </tr>
                    <tr className="bg-violet-50">
                      <td className="p-2 font-semibold">Zero at x = 4</td>
                      <td className="p-2">
                        Multiplicity 1 (odd) → graph <strong>crosses</strong>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* Remainder & Factor Theorems */}
            <div className="bg-violet-100 rounded-xl p-5 space-y-3">
              <h4 className="font-bold text-violet-900">
                Remainder Theorem & Factor Theorem
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div className="bg-white rounded-lg p-4 text-sm">
                  <p className="font-bold text-violet-800 mb-1">
                    Remainder Theorem
                  </p>
                  <p className="text-slate-600">
                    When polynomial P(x) is divided by (x − a), the remainder
                    equals <strong>P(a)</strong>. No long division needed — just
                    plug in!
                  </p>
                  <div className="font-mono mt-2 bg-violet-50 rounded p-2 text-xs">
                    <p>P(x) = x³ − 2x + 5, divide by (x − 2)</p>
                    <p className="text-violet-700 font-bold">
                      P(2) = 8 − 4 + 5 = 9 → remainder is 9
                    </p>
                  </div>
                </div>
                <div className="bg-white rounded-lg p-4 text-sm">
                  <p className="font-bold text-violet-800 mb-1">
                    Factor Theorem
                  </p>
                  <p className="text-slate-600">
                    (x − a) is a factor of P(x) if and only if{" "}
                    <strong>P(a) = 0</strong>. In other words, a is a root.
                  </p>
                  <div className="font-mono mt-2 bg-violet-50 rounded p-2 text-xs">
                    <p>P(x) = x² − 5x + 6, check x = 2:</p>
                    <p>P(2) = 4 − 10 + 6 = 0</p>
                    <p className="text-violet-700 font-bold">
                      So (x − 2) is a factor ✓
                    </p>
                  </div>
                </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">
                SAT Key Insight: Sum of Multiplicities = Degree
              </p>
              <p className="text-slate-700">
                If you're given a graph and told the degree, you can figure out
                multiplicities. For example, a degree-4 polynomial with only 3
                x-intercepts must have one zero with multiplicity 2 (a bounce).
                Use this to match graphs to equations.
              </p>
            </div>
          </div>

          <MultiplicityWidget />

          <button
            onClick={() => scrollToSection(2)}
            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 3: Quiz */}
        <section
          ref={(el) => {
            sectionsRef.current[2] = el;
          }}
          className="min-h-screen flex flex-col justify-center"
        >
          <h2 className="text-4xl font-extrabold text-slate-900 mb-8">
            Practice Time
          </h2>
          {ADV_POLYNOMIAL_QUIZ.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 PolynomialFunctionsLesson;
