import { Link } from "react-router-dom";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { CourseCard } from "@/components/CourseCard";
import { Progress } from "@/components/ui/progress";
import type { Course } from "@/data/curriculum";

type Content = Record<string, unknown>;

function str(c: unknown): string {
  return typeof c === "string" ? c : "";
}

function arr<T>(c: unknown, map: (x: unknown) => T): T[] {
  return Array.isArray(c) ? c.map(map) : [];
}

function clampCourseProgress(raw: unknown): number | undefined {
  if (raw === undefined || raw === null || raw === "") return undefined;
  const n = typeof raw === "number" ? raw : parseInt(String(raw), 10);
  if (!Number.isFinite(n)) return undefined;
  return Math.min(100, Math.max(0, n));
}

function ensureCourse(raw: unknown): Course | null {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const o = raw as Record<string, unknown>;
  const name = str(o.name).trim();
  if (!name) return null;
  const progress = clampCourseProgress(o.progress);
  const progressColorRaw = str(o.progress_color).trim() || str(o.progressColor).trim();
  return {
    name,
    emoji: str(o.emoji).trim() || "📚",
    type: (str(o.type).trim() === "dna" ? "dna" : "core") as "core" | "dna",
    whatLearning: str(o.whatLearning).trim(),
    howBuilds: str(o.howBuilds).trim(),
    keySkills: Array.isArray(o.keySkills) ? o.keySkills.map((x) => String(x)) : [],
    standards: Array.isArray(o.standards) ? o.standards.map((x) => String(x)) : [],
    portfolio: Array.isArray(o.portfolio) ? o.portfolio.map((x) => String(x)) : [],
    questionsAtHome: Array.isArray(o.questionsAtHome) ? o.questionsAtHome.map((x) => String(x)) : [],
    gapSkills: str(o.gapSkills).trim() || undefined,
    bigIdea: str(o.bigIdea).trim() || undefined,
    courseEssentialQuestion: str(o.courseEssentialQuestion).trim() || undefined,
    courseNarrative: str(o.courseNarrative).trim() || undefined,
    lens: str(o.lens).trim() || undefined,
    ...(progress !== undefined ? { progress } : {}),
    ...(progressColorRaw ? { progress_color: progressColorRaw } : {}),
  };
}

type LensItem = { name?: string; emoji?: string; type?: string; lens?: string };

function ensureLensItem(raw: unknown): LensItem {
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
    const o = raw as Record<string, unknown>;
    return {
      name: str(o.name).trim(),
      emoji: str(o.emoji).trim(),
      type: str(o.type).trim() || "core",
      lens: str(o.lens).trim(),
    };
  }
  return { name: "", emoji: "", type: "core", lens: "" };
}

function lensFromCourse(course: Course): LensItem | null {
  if (!course.lens?.trim()) return null;
  return { name: course.name, emoji: course.emoji, type: course.type, lens: course.lens };
}

const colorMap: Record<string, { bg: string; text: string; border: string }> = {
  moss: { bg: "bg-moss", text: "text-moss", border: "border-moss" },
  "deep-sea": { bg: "bg-deep-sea", text: "text-deep-sea", border: "border-deep-sea" },
  valencia: { bg: "bg-valencia", text: "text-valencia", border: "border-valencia" },
  sunflower: { bg: "bg-sunflower", text: "text-sunflower", border: "border-sunflower" },
};

const DEFAULT_RUBRIC_LABELS = ["🏗 Product", "🎤 Performance", "📊 Progress", "🤝 People", "🔥 Passion"];

type AssessmentItem = { title?: string; icon?: string; content?: string };
type PortraitDim = { dimension?: string; emoji?: string; pct?: number; description?: string };
type FinkItem = { category?: string; emoji?: string; description?: string };

/**
 * Single quarter component matching brandscape /quarter/:id:
 * flat tabs (Courses | Assessment | Evidence | Inquiry | Growth) with stacked
 * How Each Course Sees + Core + DNA under Courses.
 * Also used by slug how-each-course-sees (legacy title/items normalized upstream).
 */
export function QuarterCoursesAndLearningBlock({ content }: { content?: Content }) {
  const colorKey = str(content?.color).trim() || "moss";
  const colors = colorMap[colorKey] ?? colorMap.moss;
  const accentColor = (colorKey === "moss" || colorKey === "deep-sea" || colorKey === "valencia" || colorKey === "sunflower"
    ? colorKey
    : "moss") as "moss" | "deep-sea" | "valencia" | "sunflower";

  const coursesTabLabel = str(content?.coursesTabLabel).trim() || "Courses (13)";
  const assessmentTabLabel = str(content?.assessmentTabLabel).trim() || "Assessment";
  const evidenceTabLabel = str(content?.evidenceTabLabel).trim() || "Evidence";
  const inquiryTabLabel = str(content?.inquiryTabLabel).trim() || "Inquiry Questions";
  const growthTabLabel = str(content?.growthTabLabel).trim() || "Growth Portrait";

  const lensesTitle =
    str(content?.lensesTitle).trim() || str(content?.title).trim() || "How Each Course Sees This Quarter";
  const lensesSubtitle =
    str(content?.lensesSubtitle).trim() ||
    str(content?.subtitle).trim() ||
    "Every subject views the quarter's driving question through its own disciplinary lens.";

  const coreHeading = str(content?.coreHeading).trim() || "Core Courses";
  const coreSubtitle =
    str(content?.coreSubtitle).trim() ||
    "9 courses · year-long — taught through the lens of this quarter's driving question";
  const coreCourses: Course[] = (Array.isArray(content?.coreCourses) ? content.coreCourses : [])
    .map(ensureCourse)
    .filter((c): c is Course => c !== null);

  const dnaHeading = str(content?.dnaHeading).trim() || "DNA Strand Courses";
  const dnaSubtitle = str(content?.dnaSubtitle).trim() || "4 courses · 9 weeks — rotating specialty courses";
  const dnaCourses: Course[] = (Array.isArray(content?.dnaCourses) ? content.dnaCourses : [])
    .map(ensureCourse)
    .filter((c): c is Course => c !== null);

  const rawLensSource = Array.isArray(content?.lensesItems)
    ? content.lensesItems
    : Array.isArray(content?.items)
      ? content.items
      : [];
  const explicitLenses: LensItem[] = rawLensSource.map(ensureLensItem).filter((i) => i.lens || i.name);
  const lensItems: LensItem[] =
    explicitLenses.length > 0
      ? explicitLenses
      : [...coreCourses, ...dnaCourses].map(lensFromCourse).filter((i): i is LensItem => i !== null);

  const assessmentItems = (content?.assessmentItems as unknown[]) ?? [];
  const rubricLabels = Array.isArray(content?.rubricLabels)
    ? (content.rubricLabels as unknown[]).map((x) => String(x)).filter(Boolean)
    : DEFAULT_RUBRIC_LABELS;
  const assessmentSummaryTitle =
    str(content?.assessmentSummaryTitle).trim() || "How the Quarter Assessment Works";
  const assessmentSummary = str(content?.assessmentSummary).trim();

  const evidenceTitle = str(content?.evidenceTitle).trim() || "Evidence Portfolio";
  const evidenceSubtitle =
    str(content?.evidenceSubtitle).trim() ||
    "These work products go into your child's portfolio. Together, they tell the story of what your child learned.";
  const evidenceItems = arr(content?.evidenceItems, (x) => (typeof x === "string" ? x : String(x)));

  const inquiryTitle = str(content?.inquiryTitle).trim() || "Deep Inquiry Questions";
  const inquirySubtitle =
    str(content?.inquirySubtitle).trim() ||
    "These go beyond individual subjects — use them at dinner, on car rides, or before bed.";
  const inquiryWhyPrefix = str(content?.inquiryWhyPrefix).trim() || "Why this matters:";
  const deepInquiry = arr(content?.deepInquiry, (x) => {
    const o = x && typeof x === "object" && !Array.isArray(x) ? (x as Record<string, unknown>) : {};
    return { question: str(o.question), why: str(o.why) };
  });

  const quarterId = content?.quarterId != null ? String(content.quarterId) : "1";
  const portraitTitle = str(content?.portraitTitle).trim() || `Portrait of the Learner — Quarter ${quarterId}`;
  const portraitOfLearner = arr(content?.portraitOfLearner, (x) => {
    const o = x && typeof x === "object" && !Array.isArray(x) ? (x as Record<string, unknown>) : {};
    return {
      dimension: str(o.dimension),
      emoji: str(o.emoji),
      pct: typeof o.pct === "number" ? o.pct : 0,
      description: str(o.description),
    } as PortraitDim;
  });
  const finksTitle = str(content?.finksTitle).trim() || "Fink's Taxonomy of Significant Learning";
  const finksTaxonomy = arr(content?.finksTaxonomy, (x) => {
    const o = x && typeof x === "object" && !Array.isArray(x) ? (x as Record<string, unknown>) : {};
    return { category: str(o.category), emoji: str(o.emoji), description: str(o.description) } as FinkItem;
  });

  const navPrevLabel = str(content?.navPrevLabel).trim();
  const navPrevHref = str(content?.navPrevHref).trim();
  const navCenterLabel = str(content?.navCenterLabel).trim();
  const navCenterHref = str(content?.navCenterHref).trim();
  const navNextLabel = str(content?.navNextLabel).trim();
  const navNextHref = str(content?.navNextHref).trim();
  const hasPrevNav = Boolean(navPrevLabel && navPrevHref);
  const hasNextNav = Boolean(navNextLabel && navNextHref);
  const hasCenterNav = Boolean(navCenterLabel && navCenterHref);
  const showNavExplicit = content?.showNav;
  // Hide the whole footer when Previous and Next are both empty (Scenario 4), even if a
  // center Overview value remains from library defaults. Never invent fallback links.
  const showNav =
    showNavExplicit === false || showNavExplicit === "false"
      ? false
      : hasPrevNav || hasNextNav;

  const defaultAssessmentItems: AssessmentItem[] = [
    { title: "Week 1 · Entry Event", icon: "🎬", content: "" },
    { title: "Week 1 · Diagnostic Check", icon: "🔍", content: "" },
    { title: "Weeks 2–8 · Formative Assessment", icon: "📋", content: "" },
    { title: "Weeks 8–9 · Summative Performance", icon: "🎯", content: "" },
    { title: "How We Score: The 5P Rubric", icon: "📊", content: "" },
  ];
  const assessmentList: AssessmentItem[] =
    assessmentItems.length >= 5
      ? assessmentItems.map((x) => {
          const o = x && typeof x === "object" && !Array.isArray(x) ? (x as Record<string, unknown>) : {};
          return { title: str(o.title), icon: str(o.icon), content: str(o.content) };
        })
      : defaultAssessmentItems.map((_, i) => {
          const raw = assessmentItems[i];
          const o = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
          return {
            title: str(o.title) || defaultAssessmentItems[i]?.title,
            icon: str(o.icon) || defaultAssessmentItems[i]?.icon,
            content: str(o.content),
          };
        });

  return (
    <section className="py-10">
      <div className="container mx-auto px-6">
        <Tabs defaultValue="courses" className="w-full">
          <TabsList className="w-full justify-start overflow-x-auto flex-nowrap bg-muted mb-8 h-auto p-1 rounded-lg">
            <TabsTrigger value="courses" className="font-display text-xs sm:text-sm whitespace-nowrap">
              {coursesTabLabel}
            </TabsTrigger>
            <TabsTrigger value="assessment" className="font-display text-xs sm:text-sm whitespace-nowrap">
              {assessmentTabLabel}
            </TabsTrigger>
            <TabsTrigger value="evidence" className="font-display text-xs sm:text-sm whitespace-nowrap">
              {evidenceTabLabel}
            </TabsTrigger>
            <TabsTrigger value="inquiry" className="font-display text-xs sm:text-sm whitespace-nowrap">
              {inquiryTabLabel}
            </TabsTrigger>
            <TabsTrigger value="growth" className="font-display text-xs sm:text-sm whitespace-nowrap">
              {growthTabLabel}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="courses">
            <div className="mb-10">
              <h2 className="font-display text-2xl font-bold text-foreground mb-2">{lensesTitle}</h2>
              <p className="text-muted-foreground text-sm mb-5">{lensesSubtitle}</p>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {lensItems.map((course, idx) => (
                  <div key={course.name || idx} className="bg-muted/40 rounded-lg p-3 border border-border/50">
                    <div className="flex items-center gap-2 mb-1.5">
                      <span className="text-base">{course.emoji || "📚"}</span>
                      <span className="font-display text-xs font-semibold text-foreground">{course.name || "Course"}</span>
                      <span
                        className={`text-[9px] font-display uppercase tracking-wider px-1.5 py-0.5 rounded-full ${
                          course.type === "core" ? "bg-mist/30 text-deep-sea" : `${colors.bg}/15 text-foreground`
                        }`}
                      >
                        {course.type === "dna" ? "dna" : "core"}
                      </span>
                    </div>
                    <p className="text-muted-foreground text-xs leading-relaxed">{course.lens || ""}</p>
                  </div>
                ))}
              </div>
            </div>

            <div className="mb-8">
              <h2 className="font-display text-2xl font-bold text-foreground mb-1">{coreHeading}</h2>
              <p className="text-muted-foreground text-sm">{coreSubtitle}</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5 mb-12">
              {coreCourses.map((course) => (
                <CourseCard key={course.name} course={course} accentColor={accentColor} />
              ))}
            </div>

            <div className="mb-8">
              <h2 className="font-display text-2xl font-bold text-foreground mb-1">{dnaHeading}</h2>
              <p className="text-muted-foreground text-sm">{dnaSubtitle}</p>
            </div>
            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-5">
              {dnaCourses.map((course) => (
                <CourseCard key={course.name} course={course} accentColor={accentColor} />
              ))}
            </div>
          </TabsContent>

          <TabsContent value="assessment">
            <div className="max-w-3xl space-y-8">
              {assessmentList.map((item, idx) => (
                <div key={item.title || idx} className="bg-card rounded-xl p-6 border border-border">
                  <div className="flex items-start gap-3">
                    <span className="text-2xl">{item.icon || "📋"}</span>
                    <div>
                      <h3 className="font-display text-lg font-semibold text-foreground mb-2">{item.title}</h3>
                      <p className="text-muted-foreground leading-relaxed">{item.content}</p>
                    </div>
                  </div>
                </div>
              ))}
              {rubricLabels.length > 0 && (
                <div className="flex flex-wrap gap-3 justify-center pt-4">
                  {rubricLabels.map((p) => (
                    <span key={p} className={`${colors.bg} text-milk px-3 py-1.5 rounded-full font-display text-xs`}>
                      {p}
                    </span>
                  ))}
                </div>
              )}
              {assessmentSummary && (
                <div className="bg-card rounded-xl p-6 border border-border mt-6">
                  <h3 className="font-display text-lg font-semibold text-foreground mb-2">{assessmentSummaryTitle}</h3>
                  <p className="text-muted-foreground leading-relaxed">{assessmentSummary}</p>
                </div>
              )}
            </div>
          </TabsContent>

          <TabsContent value="evidence">
            <div className="max-w-3xl">
              <h2 className="font-display text-2xl font-bold text-foreground mb-2">{evidenceTitle}</h2>
              <p className="text-muted-foreground mb-6">{evidenceSubtitle}</p>
              <div className="space-y-3">
                {evidenceItems.map((item, i) => (
                  <div key={i} className="flex items-start gap-3 bg-card rounded-lg p-4 border border-border">
                    <div
                      className={`w-6 h-6 rounded-md border-2 ${colors.border} flex-shrink-0 mt-0.5 flex items-center justify-center`}
                    >
                      <span className="text-xs text-muted-foreground">{i + 1}</span>
                    </div>
                    <p className="text-foreground text-sm">{item}</p>
                  </div>
                ))}
              </div>
            </div>
          </TabsContent>

          <TabsContent value="inquiry">
            <div className="max-w-3xl">
              <h2 className="font-display text-2xl font-bold text-foreground mb-2">{inquiryTitle}</h2>
              <p className="text-muted-foreground mb-6">{inquirySubtitle}</p>
              <div className="space-y-4">
                {deepInquiry.map((item, i) => (
                  <div key={i} className="bg-card rounded-xl p-6 border border-border">
                    <p className={`font-display text-lg font-semibold ${colors.text} mb-2`}>"{item.question}"</p>
                    <p className="text-muted-foreground text-sm italic">
                      {inquiryWhyPrefix} {item.why}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </TabsContent>

          <TabsContent value="growth">
            <div className="max-w-4xl">
              <h2 className="font-display text-2xl font-bold text-foreground mb-6 break-words [overflow-wrap:anywhere]">
                {portraitTitle}
              </h2>
              <div className="grid md:grid-cols-2 gap-6 mb-12">
                {portraitOfLearner.map((dim, i) => (
                  <div
                    key={dim.dimension || i}
                    className="bg-card rounded-xl p-5 border border-border min-w-0 max-w-full h-auto overflow-hidden"
                  >
                    <div className="flex items-start justify-between gap-3 mb-2">
                      <span className="font-display text-sm font-semibold text-foreground min-w-0 flex-1 max-w-full whitespace-normal break-all [overflow-wrap:anywhere]">
                        {dim.emoji} {dim.dimension}
                      </span>
                      <span className={`font-display text-sm font-bold ${colors.text} shrink-0 leading-5`}>
                        {dim.pct}%
                      </span>
                    </div>
                    <Progress value={dim.pct} className="h-2 mb-2 w-full" />
                    <p className="text-muted-foreground text-xs max-w-full whitespace-normal break-all [overflow-wrap:anywhere] leading-relaxed">
                      {dim.description}
                    </p>
                  </div>
                ))}
              </div>
              <h2 className="font-display text-2xl font-bold text-foreground mb-6 break-words [overflow-wrap:anywhere]">
                {finksTitle}
              </h2>
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                {finksTaxonomy.map((item) => (
                  <div
                    key={item.category}
                    className="bg-card rounded-xl p-5 border border-border min-w-0 max-w-full h-auto overflow-hidden"
                  >
                    <span className="text-2xl block mb-2">{item.emoji}</span>
                    <h3 className="font-display text-sm font-semibold text-foreground mb-1 max-w-full whitespace-normal break-all [overflow-wrap:anywhere]">
                      {item.category}
                    </h3>
                    <p className="text-muted-foreground text-xs max-w-full whitespace-normal break-all [overflow-wrap:anywhere] leading-relaxed">
                      {item.description}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </div>

      {/* Quarter / page navigation — matches brandscape /quarter/:id footer nav */}
      {showNav && (
        <div className="py-10 bg-card border-t border-border mt-2">
          <div className="container mx-auto px-6 flex justify-between items-center gap-4">
            <div className="min-w-0 flex-1">
              {hasPrevNav ? (
                <Link
                  to={navPrevHref}
                  className="inline-flex items-center gap-2 font-display text-sm text-deep-sea hover:text-foreground transition-colors break-words"
                >
                  <ArrowLeft className="w-4 h-4 shrink-0" />
                  <span className="min-w-0">{navPrevLabel}</span>
                </Link>
              ) : null}
            </div>
            <div className="shrink-0 text-center">
              {hasCenterNav ? (
                <Link
                  to={navCenterHref}
                  className="font-display text-sm text-muted-foreground hover:text-foreground transition-colors"
                >
                  {navCenterLabel}
                </Link>
              ) : null}
            </div>
            <div className="min-w-0 flex-1 flex justify-end">
              {hasNextNav ? (
                <Link
                  to={navNextHref}
                  className="inline-flex items-center gap-2 font-display text-sm text-deep-sea hover:text-foreground transition-colors break-words text-right"
                >
                  <span className="min-w-0">{navNextLabel}</span>
                  <ArrowRight className="w-4 h-4 shrink-0" />
                </Link>
              ) : null}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
