import { defaultParentCourseOverviewContent, DEFAULT_PORTRAIT_LABELS } from "./defaultContent";
import type { LearnerCanItem, PCOSection, ParentCourseOverviewContent, TableRow } from "./types";

function str(v: unknown, fallback = ""): string {
  return typeof v === "string" ? v : fallback;
}

function rows(raw: unknown, fallback: TableRow[]): TableRow[] {
  if (!Array.isArray(raw) || raw.length === 0) return fallback.map((r) => [...r]);
  return raw.map((row) => (Array.isArray(row) ? row.map((c) => String(c ?? "")) : [String(row ?? "")]));
}

function learners(raw: unknown, fallback: LearnerCanItem[]): LearnerCanItem[] {
  if (!Array.isArray(raw) || raw.length === 0) return fallback.map((x) => ({ ...x }));
  return raw.map((item) => {
    if (typeof item === "string") return { text: item, detail: "" };
    const o = item as Record<string, unknown>;
    return {
      text: str(o.text),
      detail: str(o.detail),
      icon: str(o.icon) || undefined,
      backgroundColor: str(o.backgroundColor) || undefined,
      textColor: str(o.textColor) || undefined,
      borderColor: str(o.borderColor) || undefined,
    };
  });
}

export function buildDefaultSections(c: ParentCourseOverviewContent): PCOSection[] {
  const d = defaultParentCourseOverviewContent;
  const course = str(c.course, d.course);
  const gradeBand = str(c.gradeBand, d.gradeBand);
  const subject = str(c.subject, d.subject);
  const promise = str(c.promise, d.promise);
  const prereq = str(c.prereq, d.prereq);
  const focus = str(c.focus, d.focus);

  return [
    {
      id: "promise-snapshot",
      type: "promise-snapshot",
      enabled: true,
      number: "1.",
      title: "Course Promise + Quick Course Snapshot",
      body: promise,
      tableHeaders: ["Subject", "Course", "Grade Band", "Prerequisite / Helpful Readiness", "Parent-Friendly Focus"],
      tableRows: [[subject, course, gradeBand, prereq, focus]],
    },
    {
      id: "why-matters",
      type: "text",
      enabled: true,
      number: "2.",
      title: "Why This Course Matters",
      body: str(c.why, d.why),
    },
    {
      id: "differentiator",
      type: "text",
      enabled: true,
      number: "3.",
      title: "The Orion Differentiator",
      body: str(c.differentiator, d.differentiator),
    },
    {
      id: "portrait-spider",
      type: "portrait-spider",
      enabled: true,
      title: "Portrait of the Learner Spider Web",
      portraitSubtitle: "{course} connection to the Portrait of the Learner",
      portraitNote: str(c.portraitNote, d.portraitNote),
      portraitLabels: Array.isArray(c.portraitLabels) && c.portraitLabels.length
        ? c.portraitLabels.map(String)
        : [...(d.portraitLabels ?? DEFAULT_PORTRAIT_LABELS)],
      portraitScores: Array.isArray(c.portraitScores) && c.portraitScores.length
        ? c.portraitScores.map((n) => Number(n) || 70)
        : [...(d.portraitScores ?? [])],
    },
    {
      id: "connections",
      type: "table",
      enabled: true,
      number: "4.",
      title: `How ${course} Connects to All Learning`,
      tableHeaders: ["What other courses help with", `What ${course} adds`],
      tableRows: [[str(c.connectionsOther, d.connectionsOther), str(c.connectionsAdds, d.connectionsAdds)]],
    },
    {
      id: "learner-view",
      type: "learner-list",
      enabled: true,
      number: "5.",
      title: "From the Learner's Point of View",
      learnerItems: learners(c.learnerICan, d.learnerICan as LearnerCanItem[]),
    },
    {
      id: "gain-create",
      type: "table",
      enabled: true,
      number: "6.",
      title: "What Your Learner Will Gain and Create",
      tableHeaders: ["What learners gain", "What learners may create"],
      tableRows: [[str(c.gain, d.gain), str(c.create, d.create)]],
    },
    {
      id: "journey",
      type: "table",
      enabled: true,
      number: "7.",
      title: "Learning Journey",
      tableHeaders: ["Part of the Journey", "Learners Practice", "What Parents May Notice"],
      tableRows: rows(c.journey, d.journey ?? []),
    },
    {
      id: "across-grades",
      type: "table",
      enabled: true,
      number: "8.",
      title: `What Learning Looks Like Across ${gradeBand}`,
      tableHeaders: ["Grade Band", "What It Looks Like"],
      tableRows: rows(c.across, d.across ?? []),
    },
    {
      id: "assessment",
      type: "table",
      enabled: true,
      number: "9.",
      title: "Smarter Assessment = Less Stress",
      body: str(c.assessment, d.assessment),
      tableHeaders: ["Assessment Moment", "Question", "Evidence Parents May See"],
      tableRows: rows(c.assessmentRows, d.assessmentRows ?? []),
    },
    {
      id: "coverage",
      type: "table",
      enabled: true,
      number: "10.",
      title: "Major Coverage by Grade",
      tableHeaders: ["Grade", "Major Focus", "Prerequisite / Readiness", "Evidence Parents May See"],
      tableRows: rows(c.coverage, d.coverage ?? []),
    },
    {
      id: "portrait-connection",
      type: "table",
      enabled: true,
      number: "11.",
      title: "Connection to the Portrait of the Learner",
      tableHeaders: ["Portrait Role", "How This Course Builds It"],
      tableRows: rows(c.portraitText, d.portraitText ?? []),
    },
    {
      id: "related",
      type: "related",
      enabled: true,
      number: "12.",
      title: "Related Courses",
      body: str(c.related, d.related),
      relatedSuffix: "These courses reinforce one another rather than stand alone.",
    },
    {
      id: "home-support",
      type: "home-support",
      enabled: true,
      number: "13.",
      title: "Questions and Home Support for Families",
      body: str(c.home, d.home),
      bodySecondary:
        "Simple ways for families to support learning at home can be shared regularly during the course as part of the learning process.",
    },
    {
      id: "growth",
      type: "text",
      enabled: true,
      number: "14.",
      title: "How This Grows in Middle and Upper Grades",
      body: str(c.growth, d.growth),
    },
  ];
}

export const SECTION_TYPE_LABELS: Record<PCOSection["type"], string> = {
  "promise-snapshot": "Course Promise + Snapshot Table",
  text: "Text Section",
  "portrait-spider": "Portrait Spider Web",
  table: "Table Section",
  "learner-list": "Learner List",
  related: "Related Courses",
  "home-support": "Home Support",
};

export function createEmptySection(type: PCOSection["type"], index: number): PCOSection {
  const base = {
    id: `section-${Date.now()}-${index}`,
    type,
    enabled: true,
    title: SECTION_TYPE_LABELS[type],
    style: {},
  };
  switch (type) {
    case "promise-snapshot":
      return {
        ...base,
        number: "",
        body: "",
        tableHeaders: ["Column 1", "Column 2"],
        tableRows: [["", ""]],
      };
    case "portrait-spider":
      return {
        ...base,
        portraitSubtitle: "{course} connection to the Portrait of the Learner",
        portraitNote: "",
        portraitLabels: [...DEFAULT_PORTRAIT_LABELS],
        portraitScores: DEFAULT_PORTRAIT_LABELS.map(() => 70),
      };
    case "table":
      return {
        ...base,
        number: "",
        body: "",
        tableHeaders: ["Column 1", "Column 2"],
        tableRows: [["", ""]],
      };
    case "learner-list":
      return { ...base, number: "", learnerItems: [{ text: "", detail: "" }] };
    case "related":
      return { ...base, number: "", body: "", relatedSuffix: "" };
    case "home-support":
      return { ...base, number: "", body: "", bodySecondary: "" };
    default:
      return { ...base, number: "", body: "" };
  }
}
