import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, Target, Layers } from "lucide-react";
import SimilarityWidget from "../../../components/lessons/SimilarityWidget";
import SimilarityTestsWidget from "../../../components/lessons/SimilarityTestsWidget";
import Quiz from "../../../components/lessons/Quiz";
import { SIMILARITY_QUIZ_DATA } from "../../../utils/constants";
import { Frac } from "../../../components/Math";

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

const CongruenceSimilarityLesson: 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-rose-100" : "hover:bg-slate-100"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${isActive ? "bg-rose-600 text-white" : isPast ? "bg-rose-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-rose-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="Congruence Tests" icon={Target} />
          <SectionMarker index={1} title="Similarity Tests" icon={Layers} />
          <SectionMarker index={2} title="Proportionality" 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: Congruence */}
        <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">
            Triangle Congruence
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              Congruence means <strong>identical</strong> — same size and same
              shape, every side and every angle matches. You only need one of
              the following minimal conditions to prove two triangles congruent.
            </p>
          </div>

          <div className="bg-rose-50 border border-rose-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-rose-900">
              Congruence Tests
            </h3>

            <div className="overflow-x-auto rounded-xl border border-rose-200">
              <table className="w-full text-sm border-collapse">
                <thead>
                  <tr className="bg-rose-900 text-white">
                    <th className="p-3 text-left">Test</th>
                    <th className="p-3 text-left">Stands For</th>
                    <th className="p-3 text-left">What You Need</th>
                    <th className="p-3 text-left">Key Notes</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-rose-100">
                  <tr className="bg-rose-50">
                    <td className="p-3 font-bold text-rose-800">SSS</td>
                    <td className="p-3">Side-Side-Side</td>
                    <td className="p-3 text-slate-600">
                      All 3 pairs of sides equal
                    </td>
                    <td className="p-3 text-slate-500">Always valid</td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-3 font-bold text-rose-800">SAS</td>
                    <td className="p-3">Side-Angle-Side</td>
                    <td className="p-3 text-slate-600">
                      2 sides + angle between them
                    </td>
                    <td className="p-3 text-slate-500">
                      Angle must be included (between the sides)
                    </td>
                  </tr>
                  <tr className="bg-rose-50">
                    <td className="p-3 font-bold text-rose-800">ASA</td>
                    <td className="p-3">Angle-Side-Angle</td>
                    <td className="p-3 text-slate-600">
                      2 angles + side between them
                    </td>
                    <td className="p-3 text-slate-500">
                      Side must be between the two angles
                    </td>
                  </tr>
                  <tr className="bg-white">
                    <td className="p-3 font-bold text-rose-800">AAS</td>
                    <td className="p-3">Angle-Angle-Side</td>
                    <td className="p-3 text-slate-600">
                      2 angles + non-included side
                    </td>
                    <td className="p-3 text-slate-500">
                      Side is NOT between the two angles
                    </td>
                  </tr>
                  <tr className="bg-rose-50">
                    <td className="p-3 font-bold text-rose-800">HL</td>
                    <td className="p-3">Hypotenuse-Leg</td>
                    <td className="p-3 text-slate-600">Hypotenuse + one leg</td>
                    <td className="p-3 text-slate-500">Right triangles ONLY</td>
                  </tr>
                  <tr className="bg-slate-100">
                    <td className="p-3 font-bold text-slate-400 line-through">
                      SSA
                    </td>
                    <td className="p-3 text-slate-400 line-through">
                      Side-Side-Angle
                    </td>
                    <td className="p-3 text-rose-700 font-bold">NOT valid!</td>
                    <td className="p-3 text-rose-600">
                      Ambiguous — two triangles may fit
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            {/* CPCTC */}
            <div className="bg-white rounded-xl p-5 border border-rose-100">
              <p className="font-bold text-rose-800 mb-2">
                CPCTC — Once Proven Congruent
              </p>
              <p className="text-slate-700 text-sm">
                <strong>
                  Corresponding Parts of Congruent Triangles are Congruent.
                </strong>{" "}
                Once you've proven △ABC ≅ △DEF by any valid test, you can
                immediately state that any matching part is equal — side AB =
                DE, angle B = angle E, etc.
              </p>
            </div>

            {/* Worked Example */}
            <div className="bg-sky-50 rounded-xl p-5 border border-sky-200">
              <p className="font-bold text-sky-800 mb-3">
                Worked Example: Identifying the Test
              </p>
              <div className="text-sm text-slate-700 space-y-2">
                <p>
                  Two triangles share a common side (reflexive). One pair of
                  other sides is marked equal, and the included angles are both
                  marked as right angles.
                </p>
                <p>
                  You have: Right angle (A), common side (S), one equal side
                  (S).
                </p>
                <p className="font-bold text-sky-800">
                  → This is HL (right triangles, hypotenuse and one leg match).
                </p>
              </div>
            </div>
          </div>

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

        {/* Section 2: Similarity */}
        <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">
            Similarity Tests
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              Similarity means <strong>same shape, different size</strong>. All
              corresponding angles are equal, and all corresponding sides are
              proportional by the same scale factor k.
            </p>
          </div>

          <div className="bg-rose-50 border border-rose-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-rose-900">
              The Three Similarity Tests
            </h3>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-white rounded-xl p-4 text-center border border-rose-200">
                <p className="font-bold text-rose-900 mb-1">AA</p>
                <p className="text-sm text-slate-700">
                  2 pairs of equal angles. Most common on the SAT — if 2 angles
                  match, the third must too (triangle sum).
                </p>
              </div>
              <div className="bg-white rounded-xl p-4 text-center border border-rose-200">
                <p className="font-bold text-rose-900 mb-1">SAS~</p>
                <p className="text-sm text-slate-700">
                  2 sides in proportion + the included angle is equal.
                </p>
              </div>
              <div className="bg-white rounded-xl p-4 text-center border border-rose-200">
                <p className="font-bold text-rose-900 mb-1">SSS~</p>
                <p className="text-sm text-slate-700">
                  All 3 pairs of sides are in the same ratio k.
                </p>
              </div>
            </div>

            {/* Scale factor consequences */}
            <div className="bg-white rounded-xl p-5 border border-rose-100">
              <p className="font-bold text-rose-800 mb-3">
                What the Scale Factor k Tells You
              </p>
              <div className="overflow-x-auto rounded-xl border border-rose-200">
                <table className="w-full text-sm border-collapse">
                  <thead>
                    <tr className="bg-rose-900 text-white">
                      <th className="p-3 text-left">Measurement</th>
                      <th className="p-3 text-left">Rule</th>
                      <th className="p-3 text-left">Example (k = 3)</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-rose-100">
                    <tr className="bg-rose-50">
                      <td className="p-3">Sides / Lengths</td>
                      <td className="p-3 font-mono">× k</td>
                      <td className="p-3">Side 4 → 12</td>
                    </tr>
                    <tr className="bg-white">
                      <td className="p-3">Perimeters</td>
                      <td className="p-3 font-mono">× k</td>
                      <td className="p-3">Perimeter 18 → 54</td>
                    </tr>
                    <tr className="bg-rose-50">
                      <td className="p-3">Areas</td>
                      <td className="p-3 font-mono">× k²</td>
                      <td className="p-3">Area 10 → 90</td>
                    </tr>
                    <tr className="bg-white">
                      <td className="p-3">Angles</td>
                      <td className="p-3 font-mono">unchanged</td>
                      <td className="p-3">All angles the same</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            {/* Finding a missing side */}
            <div className="bg-sky-50 rounded-xl p-5 border border-sky-200">
              <p className="font-bold text-sky-800 mb-3">
                Worked Example: Find the Missing Side
              </p>
              <div className="font-mono text-xs text-slate-700 space-y-1">
                <p>△ABC ~ △DEF. AB = 6, BC = 9, DE = 4. Find EF.</p>
                <p>
                  k = <Frac n="DE" d="AB" /> = <Frac n="4" d="6" /> ={" "}
                  <Frac n="2" d="3" />
                </p>
                <p>
                  EF = BC × k = 9 × <Frac n="2" d="3" /> ={" "}
                  <strong className="text-sky-800">6</strong>
                </p>
              </div>
            </div>
          </div>

          <SimilarityTestsWidget />

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

        {/* Section 3: Proportionality */}
        <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">
            Triangle Proportionality
          </h2>
          <div className="prose prose-slate text-lg text-slate-600 mb-8">
            <p>
              The <strong>Triangle Proportionality Theorem</strong> states: a
              line parallel to one side of a triangle cuts the other two sides
              proportionally, creating two nested similar triangles.
            </p>
          </div>

          <div className="bg-rose-50 border border-rose-200 rounded-2xl p-6 mb-8 space-y-5">
            <h3 className="text-lg font-bold text-rose-900">
              The Proportionality Setup
            </h3>

            <div className="bg-white rounded-xl p-5 border border-rose-100">
              <p className="font-bold text-rose-800 mb-3">If DE ∥ BC, then:</p>
              <div className="grid md:grid-cols-3 gap-3 text-sm">
                <div className="bg-rose-50 rounded-lg p-3 border border-rose-100 text-center">
                  <p className="font-mono font-bold text-rose-700">
                    <Frac n="AD" d="DB" /> = <Frac n="AE" d="EC" />
                  </p>
                  <p className="text-xs text-slate-600 mt-1">
                    sides cut proportionally
                  </p>
                </div>
                <div className="bg-rose-50 rounded-lg p-3 border border-rose-100 text-center">
                  <p className="font-mono font-bold text-rose-700">
                    △ADE ~ △ABC
                  </p>
                  <p className="text-xs text-slate-600 mt-1">
                    by AA similarity
                  </p>
                </div>
                <div className="bg-rose-50 rounded-lg p-3 border border-rose-100 text-center">
                  <p className="font-mono font-bold text-rose-700">
                    <Frac n="AD" d="AB" /> = <Frac n="AE" d="AC" /> ={" "}
                    <Frac n="DE" d="BC" />
                  </p>
                  <p className="text-xs text-slate-600 mt-1">
                    all ratios equal
                  </p>
                </div>
              </div>
            </div>

            {/* Worked Examples */}
            <div className="space-y-3">
              <div className="bg-sky-50 rounded-xl p-4 border border-sky-200 text-sm">
                <p className="font-semibold text-sky-800 mb-2">
                  Worked Example 1: Find a segment length
                </p>
                <div className="font-mono text-xs text-slate-700 space-y-1">
                  <p>DE ∥ BC. AD = 4, DB = 6, AE = 5. Find EC.</p>
                  <p>
                    <Frac n="AD" d="DB" /> = <Frac n="AE" d="EC" />
                  </p>
                  <p>
                    <Frac n="4" d="6" /> = <Frac n="5" d="EC" />
                  </p>
                  <p>
                    EC = <Frac n="5 × 6" d="4" /> = <Frac n="30" d="4" /> ={" "}
                    <strong className="text-sky-800">7.5</strong>
                  </p>
                </div>
              </div>
              <div className="bg-sky-50 rounded-xl p-4 border border-sky-200 text-sm">
                <p className="font-semibold text-sky-800 mb-2">
                  Worked Example 2: Find side DE
                </p>
                <div className="font-mono text-xs text-slate-700 space-y-1">
                  <p>DE ∥ BC. AD = 3, AB = 9, BC = 12. Find DE.</p>
                  <p>
                    k = <Frac n="AD" d="AB" /> = <Frac n="3" d="9" /> ={" "}
                    <Frac n="1" d="3" />
                  </p>
                  <p>
                    DE = BC × k = 12 × <Frac n="1" d="3" /> ={" "}
                    <strong className="text-sky-800">4</strong>
                  </p>
                </div>
              </div>
              <div className="bg-sky-50 rounded-xl p-4 border border-sky-200 text-sm">
                <p className="font-semibold text-sky-800 mb-2">
                  Worked Example 3: Find area ratio
                </p>
                <div className="font-mono text-xs text-slate-700 space-y-1">
                  <p>
                    △ADE ~ △ABC with k = <Frac n="1" d="3" />. If Area(ABC) =
                    27, find Area(ADE).
                  </p>
                  <p>
                    Area scales by k² = (<Frac n="1" d="3" />
                    )² = <Frac n="1" d="9" />
                  </p>
                  <p>
                    Area(ADE) = 27 × <Frac n="1" d="9" /> ={" "}
                    <strong className="text-sky-800">3</strong>
                  </p>
                </div>
              </div>
            </div>

            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm">
              <p className="font-bold text-amber-900 mb-1">
                SAT Strategy: Spot the Parallel Line
              </p>
              <p className="text-slate-700">
                When you see a triangle with a line drawn parallel to one side
                (look for tick marks or stated conditions), immediately set up a
                proportion using the segments. This is usually solvable in 2–3
                steps.
              </p>
            </div>
          </div>

          <SimilarityWidget />

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

export default CongruenceSimilarityLesson;
