import React, { useRef, useState, useEffect } from "react";
import { Check, ChevronDown, ChevronUp, ChevronRight } from "lucide-react";
import type { PracticeQuestion } from "../../types/lesson";
import {
  transformMathHtml,
  isQuestionBroken,
} from "../../utils/mathHtmlTransform";

export interface SectionDef {
  title: string;
  icon: React.ComponentType<{ className?: string }>;
}

interface LessonShellProps {
  title: string;
  sections: SectionDef[];
  color: "blue" | "violet" | "amber" | "emerald";
  onFinish?: () => void;
  children: React.ReactNode;
}

/* ─── colour palette for each category ─── */
const PALETTES = {
  blue: {
    activeBg: "bg-blue-600",
    activeText: "text-blue-900",
    pastBg: "bg-blue-400",
    sidebarActive:
      "bg-white/80 shadow-md border border-blue-100 lg:bg-transparent lg:shadow-none lg:border-transparent",
    dotBg: "bg-blue-100",
    dotText: "text-blue-500",
    glassClass: "glass-blue",
  },
  violet: {
    activeBg: "bg-violet-600",
    activeText: "text-violet-900",
    pastBg: "bg-violet-400",
    sidebarActive:
      "bg-white/80 shadow-md border border-violet-100 lg:bg-transparent lg:shadow-none lg:border-transparent",
    dotBg: "bg-violet-100",
    dotText: "text-violet-500",
    glassClass: "glass-violet",
  },
  amber: {
    activeBg: "bg-amber-600",
    activeText: "text-amber-900",
    pastBg: "bg-amber-400",
    sidebarActive:
      "bg-white/80 shadow-md border border-amber-100 lg:bg-transparent lg:shadow-none lg:border-transparent",
    dotBg: "bg-amber-100",
    dotText: "text-amber-500",
    glassClass: "glass-amber",
  },
  emerald: {
    activeBg: "bg-emerald-600",
    activeText: "text-emerald-900",
    pastBg: "bg-emerald-400",
    sidebarActive:
      "bg-white/80 shadow-md border border-emerald-100 lg:bg-transparent lg:shadow-none lg:border-transparent",
    dotBg: "bg-emerald-100",
    dotText: "text-emerald-500",
    glassClass: "glass-emerald",
  },
};

export default function LessonShell({
  title,
  sections,
  color,
  onFinish,
  children,
}: LessonShellProps) {
  const palette = PALETTES[color];
  const [activeSection, setActiveSection] = useState(0);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const sectionsRef = useRef<(HTMLElement | null)[]>([]);

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

  /* scroll-spy */
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const idx = sectionsRef.current.indexOf(
              entry.target as HTMLElement,
            );
            if (idx !== -1) setActiveSection(idx);
          }
        });
      },
      { rootMargin: "-20% 0px -60% 0px" },
    );
    sectionsRef.current.forEach((s) => {
      if (s) observer.observe(s);
    });
    return () => observer.disconnect();
  }, []);

  /* Inject ref callbacks onto section-wrapper children */
  const childArray = React.Children.toArray(children);

  return (
    <div className="flex flex-col lg:flex-row min-h-screen lesson-bg">
      {/* ── Mobile toggle ── */}
      <button
        onClick={() => setSidebarOpen(!sidebarOpen)}
        className="lg:hidden fixed bottom-4 right-4 z-50 flex items-center gap-2 px-4 py-2.5 rounded-full shadow-lg text-sm font-bold text-slate-700 bg-white"
      >
        {sidebarOpen ? (
          <ChevronDown className="w-4 h-4" />
        ) : (
          <ChevronUp className="w-4 h-4" />
        )}
        {sections[activeSection]?.title ?? "Sections"}
      </button>

      {/* ── Sidebar ── */}
      <aside
        className={`
          ${sidebarOpen ? "translate-y-0" : "translate-y-full lg:translate-y-0"}
          fixed bottom-0 left-0 right-0 lg:top-20 lg:bottom-0 lg:left-0 lg:right-auto
          w-full lg:w-64 z-40 lg:z-0
          glass-sidebar p-4 lg:overflow-y-auto
          transition-transform duration-300 ease-out
          rounded-t-2xl lg:rounded-none
          border-t lg:border-t-0 border-slate-200/50
        `}
      >
        <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-slate-400 mb-3 px-1 hidden lg:block">
          Sections
        </p>
        <nav className="space-y-1.5 bg-white lg:bg-transparent">
          {sections.map((sec, i) => {
            const isActive = activeSection === i;
            const isPast = activeSection > i;
            const Icon = sec.icon;
            return (
              <button
                key={i}
                onClick={() => scrollToSection(i)}
                className={`flex  items-center gap-3 p-2.5 w-full rounded-xl transition-all text-left ${
                  isActive
                    ? palette.sidebarActive
                    : "hover:bg-white/50 lg:hover:bg-transparent"
                }`}
              >
                <div
                  className={`w-7 h-7 rounded-lg flex items-center justify-center shrink-0 transition-colors ${
                    isActive
                      ? `${palette.activeBg} text-white`
                      : isPast
                        ? `${palette.pastBg} text-white`
                        : `${palette.dotBg} ${palette.dotText}`
                  }`}
                >
                  {isPast ? (
                    <Check className="w-3.5 h-3.5" />
                  ) : (
                    <Icon className="w-3.5 h-3.5" />
                  )}
                </div>
                <span
                  className={`text-xs font-semibold leading-tight ${isActive ? palette.activeText : "text-slate-600"}`}
                >
                  {sec.title}
                </span>
              </button>
            );
          })}
        </nav>
      </aside>

      {/* ── Main content ── */}
      <div className="flex-1 lg:ml-64 max-w-4xl mx-auto w-full">
        {childArray.map((child, i) => (
          <section
            key={i}
            ref={(el) => {
              sectionsRef.current[i] = el;
            }}
            className="min-h-[70vh] mb-20 pt-16 lg:pt-4"
          >
            {child}

            {/* next-section / finish button */}
            {i < sections.length - 1 ? (
              <button
                onClick={() => scrollToSection(i + 1)}
                className={`mt-10 group flex items-center gap-2 font-bold transition-colors ${
                  color === "blue"
                    ? "text-blue-600 hover:text-blue-800"
                    : color === "violet"
                      ? "text-violet-600 hover:text-violet-800"
                      : color === "amber"
                        ? "text-amber-600 hover:text-amber-800"
                        : "text-emerald-600 hover:text-emerald-800"
                }`}
              >
                Next: {sections[i + 1]?.title}
                <ChevronRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
              </button>
            ) : onFinish ? (
              <button
                onClick={onFinish}
                className="mt-10 px-8 py-3 rounded-xl bg-linear-to-r from-slate-800 to-slate-900 text-white font-bold shadow-lg hover:from-slate-700 hover:to-slate-800 transition-all hover:scale-[1.02]"
              >
                Complete Lesson
              </button>
            ) : null}
          </section>
        ))}
      </div>
    </div>
  );
}

/* ─── Reusable concept-card wrapper ─── */
export function ConceptCard({
  color = "blue",
  children,
  className = "",
}: {
  color?: "blue" | "violet" | "amber" | "emerald";
  children: React.ReactNode;
  className?: string;
}) {
  const glassClass =
    color === "blue"
      ? "glass-blue"
      : color === "violet"
        ? "glass-violet"
        : color === "amber"
          ? "glass-amber"
          : "glass-emerald";
  return (
    <div
      className={`${glassClass} glass-card rounded-2xl p-6 mb-8 space-y-5 ${className}`}
    >
      {children}
    </div>
  );
}

/* ─── Formula display box ─── */
export function FormulaBox({
  children,
  className = "",
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <div
      className={`glass-formula text-center py-4 px-6 font-mono text-lg font-bold text-slate-800 ${className}`}
    >
      {children}
    </div>
  );
}

/* ─── Worked-example card ─── */
export function ExampleCard({
  title,
  color = "blue",
  children,
}: {
  title: string;
  color?: "blue" | "violet" | "amber" | "emerald";
  children: React.ReactNode;
}) {
  const border =
    color === "blue"
      ? "border-blue-200 bg-gradient-to-br from-blue-50/60 to-indigo-50/40"
      : color === "violet"
        ? "border-violet-200 bg-gradient-to-br from-violet-50/60 to-purple-50/40"
        : color === "amber"
          ? "border-amber-200 bg-gradient-to-br from-amber-50/60 to-orange-50/40"
          : "border-emerald-200 bg-gradient-to-br from-emerald-50/60 to-green-50/40";
  const titleColor =
    color === "blue"
      ? "text-blue-800"
      : color === "violet"
        ? "text-violet-800"
        : color === "amber"
          ? "text-amber-800"
          : "text-emerald-800";
  return (
    <div className={`rounded-xl border ${border} p-5`}>
      <p className={`font-bold ${titleColor} mb-3`}>{title}</p>
      <div className="font-mono text-sm space-y-1 text-slate-700">
        {children}
      </div>
    </div>
  );
}

/* ─── Tip / Warning card ─── */
export function TipCard({
  type = "tip",
  children,
}: {
  type?: "tip" | "warning" | "remember";
  children: React.ReactNode;
}) {
  const style =
    type === "warning"
      ? "bg-red-50/70 border-red-200 text-red-900"
      : type === "remember"
        ? "bg-amber-50/70 border-amber-200 text-amber-900"
        : "bg-blue-50/70 border-blue-200 text-blue-900";
  const label =
    type === "warning"
      ? "Common Mistake"
      : type === "remember"
        ? "Remember"
        : "SAT Tip";
  return (
    <div className={`rounded-xl border p-4 text-sm ${style}`}>
      <p className="font-bold mb-1">{label}</p>
      {children}
    </div>
  );
}

/* ─── Practice question from dataset ─── */
type PracticeColor =
  | "blue"
  | "violet"
  | "amber"
  | "emerald"
  | "teal"
  | "fuchsia"
  | "rose"
  | "purple";

export function PracticeFromDataset({
  question,
  color = "blue",
}: {
  key?: React.Key;
  question: PracticeQuestion;
  color?: PracticeColor;
}) {
  const [selected, setSelected] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [sprInput, setSprInput] = useState("");

  const isCorrect =
    question.type === "mcq"
      ? selected === question.correctAnswer
      : (() => {
          const u = sprInput.trim().toLowerCase();
          const answers = question.correctAnswer
            .split(",")
            .map((a) => a.trim().toLowerCase());
          if (answers.includes(u)) return true;
          const toNum = (s: string): number | null => {
            if (s.includes("/")) {
              const p = s.split("/");
              return p.length === 2
                ? parseFloat(p[0]) / parseFloat(p[1])
                : null;
            }
            const n = parseFloat(s);
            return isNaN(n) ? null : n;
          };
          const uN = toNum(u);
          return (
            uN !== null &&
            answers.some((a) => {
              const aN = toNum(a);
              return aN !== null && Math.abs(uN - aN) < 0.0015;
            })
          );
        })();

  const handleSubmit = () => {
    if (question.type === "mcq" && !selected) return;
    if (question.type === "spr" && !sprInput.trim()) return;
    setSubmitted(true);
  };

  const accentMap: Record<PracticeColor, string> = {
    blue: "border-blue-500 bg-blue-50",
    violet: "border-violet-500 bg-violet-50",
    amber: "border-amber-500 bg-amber-50",
    emerald: "border-emerald-500 bg-emerald-50",
    teal: "border-teal-500 bg-teal-50",
    fuchsia: "border-fuchsia-500 bg-fuchsia-50",
    rose: "border-rose-500 bg-rose-50",
    purple: "border-purple-500 bg-purple-50",
  };
  const accent = accentMap[color] ?? accentMap.blue;

  // Skip broken questions
  if (isQuestionBroken(question)) return null;

  return (
    <div className="glass-card rounded-2xl p-5 mb-6 space-y-4">
      {/* Passage (EBRW questions) */}
      {question.passage && (
        <div className="bg-linear-to-b from-slate-50 to-white rounded-xl border border-slate-200 p-4 text-sm text-slate-700 leading-relaxed max-h-60 overflow-y-auto">
          <p className="text-[10px] font-extrabold text-slate-400 uppercase tracking-widest mb-2">
            Passage
          </p>
          <div dangerouslySetInnerHTML={{ __html: question.passage }} />
        </div>
      )}

      {question.hasFigure && question.figureUrl && (
        <img
          src={question.figureUrl}
          alt="Figure"
          className="max-w-full max-h-80 mx-auto rounded-xl border border-slate-200"
        />
      )}
      <div
        className="text-sm text-slate-700 leading-relaxed"
        dangerouslySetInnerHTML={{
          __html: transformMathHtml(question.questionHtml),
        }}
      />

      {question.type === "mcq" ? (
        <div className="space-y-2">
          {question.choices.map((c) => {
            const isThis = selected === c.label;
            let ring = "border-slate-200 hover:border-slate-300";
            if (submitted && isThis)
              ring = isCorrect
                ? "border-emerald-500 bg-emerald-50"
                : "border-red-400 bg-red-50";
            else if (submitted && c.label === question.correctAnswer)
              ring = "border-emerald-500 bg-emerald-50";
            else if (isThis) ring = accent;
            const isTable = c.text.includes("<br><br>");
            return (
              <button
                key={c.label}
                onClick={() => !submitted && setSelected(c.label)}
                disabled={submitted}
                className={`w-full text-left flex items-center gap-3 p-3 rounded-xl border transition-all text-sm ${ring}`}
              >
                <span className="w-7 h-7 rounded-full border border-current flex items-center justify-center text-xs font-bold shrink-0">
                  {c.label}
                </span>
                <div
                  className={`flex-1 ${isTable ? "columns-2 gap-8" : ""}`}
                  dangerouslySetInnerHTML={{
                    __html: transformMathHtml(c.text),
                  }}
                />
              </button>
            );
          })}
        </div>
      ) : (
        <input
          type="text"
          value={sprInput}
          onChange={(e) => !submitted && setSprInput(e.target.value)}
          disabled={submitted}
          placeholder="Type your answer…"
          className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"
        />
      )}

      {!submitted ? (
        <button
          onClick={handleSubmit}
          className="px-5 py-2 rounded-xl bg-slate-800 text-white text-sm font-bold hover:bg-slate-700 transition-colors"
        >
          Check Answer
        </button>
      ) : (
        <div
          className={`rounded-xl border p-4 text-sm ${isCorrect ? "bg-emerald-50/70 border-emerald-200" : "bg-slate-50 border-slate-200"}`}
        >
          <p
            className={`font-bold mb-1 ${isCorrect ? "text-emerald-700" : "text-red-600"}`}
          >
            {isCorrect
              ? "Correct!"
              : `Incorrect — the answer is ${question.correctAnswer}`}
          </p>
          <div
            className="text-slate-600 leading-relaxed"
            dangerouslySetInnerHTML={{
              __html: transformMathHtml(question.explanation),
            }}
          />
        </div>
      )}
    </div>
  );
}
