import React, { useRef, useState, useEffect } from "react";
import { ArrowDown, Check, BookOpen, AlertTriangle, Zap } from "lucide-react";
import { PracticeFromDataset } from "../../../components/lessons/LessonShell";
import {
  FORM_STRUCTURE_EASY,
  FORM_STRUCTURE_MEDIUM,
} from "../../../data/rw/form-structure-sense";
import ClauseBreakdownWidget, {
  type ClauseExample,
} from "../../../components/lessons/ClauseBreakdownWidget";
import DecisionTreeWidget, {
  type TreeScenario,
  type TreeNode,
} from "../../../components/lessons/DecisionTreeWidget";

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

// ── Clause Breakdown data ──────────────────────────────────────────────────
const CLAUSE_EXAMPLES: ClauseExample[] = [
  {
    title: "Verb Tense — Past Sequence",
    segments: [
      {
        text: "By the time the results arrived",
        type: "dc",
        label: "Dependent Clause — earlier action",
      },
      { text: ",", type: "punct" },
      {
        text: " the team had already published",
        type: "verb",
        label: "Past Perfect: action completed before another past action",
      },
      { text: " their findings", type: "ic", label: "" },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Subjunctive Mood",
    segments: [
      {
        text: "If the data were",
        type: "dc",
        label: "Subjunctive: 'were' not 'was' — hypothetical condition",
      },
      { text: " more complete", type: "ic", label: "" },
      { text: ",", type: "punct" },
      {
        text: " the conclusions would be stronger",
        type: "ic",
        label: "Main clause with 'would'",
      },
      { text: ".", type: "punct" },
    ],
  },
  {
    title: "Gerund vs. Infinitive",
    segments: [
      { text: "The committee", type: "subject", label: "Subject" },
      {
        text: " decided",
        type: "verb",
        label: "Verb: 'decided' takes infinitive",
      },
      {
        text: " to postpone",
        type: "conjunction",
        label: "Infinitive: 'to + verb'",
      },
      { text: " the vote", type: "ic", label: "" },
      { text: ".", type: "punct" },
    ],
  },
];

// ── Decision Tree data ─────────────────────────────────────────────────────
const VERB_TREE: TreeNode = {
  id: "root",
  question: "What verb form problem is in this sentence?",
  hint: "Is it about: (1) tense consistency/sequence, (2) subjunctive mood (if/wish), or (3) verb form (gerund '-ing' vs. infinitive 'to-verb')?",
  yesLabel: "Tense or sequence issue",
  noLabel: "Subjunctive or verb form issue",
  yes: {
    id: "tense",
    question:
      "Does the sentence describe an action that happened BEFORE another past action?",
    hint: "'By the time X happened, Y had already...' — the earlier action needs past perfect (had + verb).",
    yesLabel: "Yes — one action preceded another",
    noLabel: "No — all actions at the same time",
    yes: {
      id: "past-perfect",
      result:
        "✓ Use PAST PERFECT (had + past participle) for the earlier action: 'had published,' 'had discovered,' 'had completed.'",
      resultType: "correct",
      ruleRef: "Earlier: had + [past participle] | Later: simple past",
    },
    no: {
      id: "tense-consistency",
      result:
        "✓ Keep tense CONSISTENT with the surrounding context. If the passage is in past tense, don't switch to present or future unnecessarily.",
      resultType: "correct",
      ruleRef: "Match the dominant tense of the passage",
    },
  },
  no: {
    id: "subj-or-form",
    question:
      "Does the sentence contain 'if,' 'wish,' 'as if,' or 'as though' — expressing a hypothetical or contrary-to-fact condition?",
    yesLabel: "Yes — hypothetical or wish",
    noLabel: "No — it's about gerund vs. infinitive",
    yes: {
      id: "subjunctive",
      question:
        "Is the condition clearly FALSE or hypothetical (not likely to be true)?",
      yesLabel: "Yes — clearly hypothetical",
      noLabel: "No — it could be real/possible",
      yes: {
        id: "subjunctive-were",
        result:
          "✓ Use SUBJUNCTIVE WERE (not 'was'): 'If the data were complete...' / 'I wish the study were larger.'",
        resultType: "correct",
        ruleRef:
          "Hypothetical: If [subject] were... / I wish [subject] were...",
      },
      no: {
        id: "indicative-if",
        result:
          "✓ Use indicative 'was' — the condition is possible, not hypothetical: 'If the data was incorrect, we would know by now.'",
        resultType: "correct",
        ruleRef: "Possible condition: If [subject] was...",
      },
    },
    no: {
      id: "gerund-infinitive",
      question:
        "Does the main verb PREFER a gerund (enjoy, avoid, consider, suggest) or an infinitive (decide, want, plan, need)?",
      hint: "Gerund (-ing): 'The team avoided making errors.' Infinitive (to-verb): 'The team decided to revise.'",
      yesLabel: "Gerund (-ing) after this verb",
      noLabel: "Infinitive (to-verb) after this verb",
      yes: {
        id: "use-gerund",
        result:
          "✓ Use the GERUND (-ing form): avoid, enjoy, consider, suggest, recommend → 'avoid making,' 'enjoy reading.'",
        resultType: "correct",
        ruleRef: "avoid/enjoy/consider + [verb]-ing",
      },
      no: {
        id: "use-infinitive",
        result:
          "✓ Use the INFINITIVE (to + verb): decide, want, need, plan, hope, agree → 'decided to publish,' 'hoped to complete.'",
        resultType: "correct",
        ruleRef: "decide/want/need/plan + to [verb]",
      },
    },
  },
};

const TREE_SCENARIOS: TreeScenario[] = [
  {
    label: "Sentence 1",
    sentence:
      "By the time the paper was published, the researchers already discovered three additional variables.",
    tree: VERB_TREE,
  },
  {
    label: "Sentence 2",
    sentence:
      "If the sample size was larger, the study's conclusions would be more reliable.",
    tree: VERB_TREE,
  },
  {
    label: "Sentence 3",
    sentence:
      "The committee recommended to adopt the new protocol before the next review cycle.",
    tree: VERB_TREE,
  },
];

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

  useEffect(() => {
    const observers: IntersectionObserver[] = [];
    sectionsRef.current.forEach((el, idx) => {
      if (!el) return;
      const obs = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) setActiveSection(idx);
        },
        { threshold: 0.3 },
      );
      obs.observe(el);
      observers.push(obs);
    });
    return () => observers.forEach((o) => o.disconnect());
  }, []);

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

  const SectionMarker = ({
    index,
    title,
    icon: Icon,
  }: {
    index: number;
    title: string;
    icon: React.ElementType;
  }) => {
    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 text-left transition-all ${isActive ? "bg-purple-50" : "hover:bg-slate-50"}`}
      >
        <div
          className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0
          ${isActive ? "bg-purple-600 text-white" : isPast ? "bg-purple-400 text-white" : "bg-slate-200 text-slate-500"}`}
        >
          {isPast ? (
            <Check className="w-4 h-4" />
          ) : (
            <Icon className="w-4 h-4" />
          )}
        </div>
        <p
          className={`text-sm font-bold ${isActive ? "text-purple-900" : "text-slate-600"}`}
        >
          {title}
        </p>
      </button>
    );
  };

  return (
    <div className="flex flex-col lg:flex-row min-h-screen">
      <aside className="w-full lg:w-64 lg:fixed lg:top-14 lg:bottom-0 lg:overflow-y-auto p-4 border-r border-slate-200 bg-slate-50 z-0 hidden lg:block">
        <nav className="space-y-2 pt-6">
          <SectionMarker index={0} title="Verb Anatomy" icon={BookOpen} />
          <SectionMarker
            index={1}
            title="Decision Tree Lab"
            icon={AlertTriangle}
          />
          <SectionMarker index={2} title="Practice Questions" icon={Zap} />
        </nav>
      </aside>

      <div className="flex-1 lg:ml-64 p-6 md:p-12 max-w-4xl mx-auto">
        {/* Section 0 — Concept + Clause Breakdown */}
        <section
          ref={(el) => {
            sectionsRef.current[0] = el;
          }}
          className="min-h-screen flex flex-col justify-center mb-24 pt-20 lg:pt-0"
        >
          <div className="inline-flex items-center gap-2 bg-purple-100 text-purple-700 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider mb-4 w-fit">
            Standard English Conventions
          </div>
          <h2 className="text-4xl font-extrabold text-slate-900 mb-2">
            Verb Anatomy
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            See how verb tense, mood, and form work in context — then apply the
            rules.
          </p>

          {/* Rule summary grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-8">
            {[
              {
                num: 1,
                rule: "Tense Consistency",
                desc: "Match the dominant tense of the passage. Don't randomly shift.",
              },
              {
                num: 2,
                rule: "Past Perfect",
                desc: "Use 'had + verb' for the earlier of two past events.",
              },
              {
                num: 3,
                rule: "Subjunctive Were",
                desc: "Hypothetical conditions: 'If [subject] were...' regardless of singular/plural.",
              },
              {
                num: 4,
                rule: "Gerund vs. Infinitive",
                desc: "Certain verbs take gerunds; others take infinitives. Memory: avoid/enjoy/consider + -ing. decide/want/plan + to-verb.",
              },
            ].map((r) => (
              <div
                key={r.num}
                className="bg-purple-50 border border-purple-200 rounded-xl p-4"
              >
                <div className="flex items-center gap-2 mb-1">
                  <span className="w-6 h-6 rounded-full bg-purple-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
                    {r.num}
                  </span>
                  <span className="font-bold text-purple-900 text-sm">
                    {r.rule}
                  </span>
                </div>
                <p className="text-xs text-slate-600 ml-8">{r.desc}</p>
              </div>
            ))}
          </div>

          {/* Clause Breakdown */}
          <h3 className="text-xl font-bold text-slate-800 mb-3">
            Sentence Anatomy
          </h3>
          <p className="text-sm text-slate-500 mb-4">
            Hover over any colored span to see its label. Use the tabs to switch
            between examples.
          </p>
          <ClauseBreakdownWidget
            examples={CLAUSE_EXAMPLES}
            accentColor="purple"
          />

          {/* Traps */}
          <div className="mt-8 space-y-3 mb-8">
            {[
              {
                label: "Past Perfect vs. Simple Past",
                desc: "'had already published' (earlier) vs. 'published' (simple past). Don't confuse sequence with simultaneity.",
              },
              {
                label: "Was vs. Were (Subjunctive)",
                desc: "Hypothetical conditions use 'were' even with singular subjects: 'If she were the lead researcher...'",
              },
              {
                label: "Gerund/Infinitive Collocations",
                desc: "'suggest to do' is wrong; 'suggest doing' is correct. 'decide doing' is wrong; 'decide to do' is correct.",
              },
            ].map((t) => (
              <div
                key={t.label}
                className="flex gap-3 bg-red-50 border border-red-200 rounded-xl px-4 py-3"
              >
                <AlertTriangle className="w-4 h-4 text-red-500 shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-bold text-red-800">{t.label}</p>
                  <p className="text-xs text-slate-600 mt-0.5">{t.desc}</p>
                </div>
              </div>
            ))}
          </div>

          <div className="mt-2 bg-purple-900 text-white rounded-2xl p-5">
            <p className="font-bold mb-1">Golden Rule</p>
            <p className="text-sm text-purple-100">
              Three verb traps dominate the SAT: mixing tenses in a sequence,
              missing the subjunctive "were" in hypotheticals, and using the
              wrong verb form (gerund/infinitive). Always check the time
              relationship and the main verb's preference.
            </p>
          </div>

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

        {/* Section 1 — Decision Tree */}
        <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-2">
            Decision Tree Lab
          </h2>
          <p className="text-lg text-slate-500 mb-8">
            Work through the verb logic one question at a time. Click your
            answer at each step.
          </p>

          <DecisionTreeWidget scenarios={TREE_SCENARIOS} accentColor="purple" />

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

        {/* Section 2 — Quiz */}
        <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">
            Practice Questions
          </h2>
          {FORM_STRUCTURE_EASY.slice(4, 6).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="purple" />
          ))}
          {FORM_STRUCTURE_MEDIUM.slice(2, 3).map((q) => (
            <PracticeFromDataset key={q.id} question={q} color="purple" />
          ))}
          <div className="mt-8 text-center">
            <button
              onClick={onFinish}
              className="px-6 py-3 bg-purple-900 text-white font-bold rounded-full hover:bg-purple-700 transition-colors"
            >
              Finish Lesson ✓
            </button>
          </div>
        </section>
      </div>
    </div>
  );
};

export default EBRWVerbsLesson;
