import { Link } from "react-router-dom";
import { motion } from "framer-motion";
import { fadeUpItem } from "@/components/PageTransition";

type Content = Record<string, unknown>;

type CycleStep = { step: string; title: string; desc: string };
type TimelinePhase = { period: string; title: string; emoji: string; items: string[] };

const defaultHeading = "Problem-Based Experiential Learning";
const defaultTitle = "💧 PBEL: Water — Every Drop Counts";
const defaultSubtitle =
  "Students learn by tackling real community challenges through design thinking and service learning — this year's theme connects global water issues to local action.";
const defaultCycleTitle = "🔄 The PBEL Cycle";
const defaultCycleSteps: CycleStep[] = [
  { step: "1", title: "Investigate & Empathize", desc: "Observe, interview, and collect baseline data" },
  { step: "2", title: "Define & Ideate", desc: "Craft 'How might we…?' questions and brainstorm" },
  { step: "3", title: "Prototype & Test", desc: "Build models and run small pilots" },
  { step: "4", title: "Implement & Serve", desc: "Deploy solutions with partners, track results" },
  { step: "5", title: "Reflect & Demonstrate", desc: "Present at Innovation & Impact Showcase" },
];
const defaultTimelineTitle = "📅 Year Timeline";
const defaultTimelinePhases: TimelinePhase[] = [
  { period: "Sep–Oct", title: "Discover & Define", emoji: "🔍", items: ["Investigations & empathy interviews", "Baseline data collected", "Early 'quick-win' nudges"] },
  { period: "Nov–Jan", title: "Prototype & Pilot", emoji: "🔧", items: ["Build simple models and test", "One short pilot per team"] },
  { period: "Feb–May", title: "Implement & Demonstrate", emoji: "🚀", items: ["Scale what works with partners", "Track savings & adoption", "Innovation & Impact Showcase"] },
];
const defaultLinkText = "💧 Explore the Full PBEL Guide →";
const defaultLinkHref = "/course/pbel-water";

function ensureCycleStep(raw: unknown): CycleStep {
  if (raw && typeof raw === "object" && "title" in raw) {
    const o = raw as Record<string, unknown>;
    return {
      step: typeof o.step === "string" ? o.step : "",
      title: typeof o.title === "string" ? o.title : "",
      desc: typeof o.desc === "string" ? o.desc : "",
    };
  }
  return { step: "", title: "", desc: "" };
}

function ensureTimelinePhase(raw: unknown): TimelinePhase {
  if (raw && typeof raw === "object" && "title" in raw) {
    const o = raw as Record<string, unknown>;
    const items = Array.isArray(o.items) ? o.items.map((i) => (typeof i === "string" ? i : "")) : [];
    return {
      period: typeof o.period === "string" ? o.period : "",
      title: typeof o.title === "string" ? o.title : "",
      emoji: typeof o.emoji === "string" ? o.emoji : "📌",
      items,
    };
  }
  return { period: "", title: "", emoji: "📌", items: [] };
}

export function PbelBlock({ content }: { content?: Content }) {
  const heading = (content?.heading as string) ?? defaultHeading;
  const title = (content?.title as string) ?? defaultTitle;
  const subtitle = (content?.subtitle as string) ?? defaultSubtitle;
  const cycleTitle = (content?.cycleTitle as string) ?? defaultCycleTitle;
  const rawSteps = content?.cycleSteps;
  const cycleSteps: CycleStep[] = Array.isArray(rawSteps) ? rawSteps.map(ensureCycleStep) : defaultCycleSteps;
  const timelineTitle = (content?.timelineTitle as string) ?? defaultTimelineTitle;
  const rawPhases = content?.timelinePhases;
  const timelinePhases: TimelinePhase[] = Array.isArray(rawPhases) ? rawPhases.map(ensureTimelinePhase) : defaultTimelinePhases;
  const linkText = (content?.linkText as string) ?? defaultLinkText;
  const linkHref = (content?.linkHref as string) ?? defaultLinkHref;

  return (
    <motion.section
      className="py-16 md:py-24 bg-background"
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
    >
      <div className="container mx-auto px-6 max-w-5xl">
        <div className="text-center mb-12">
          <p className="font-display text-xs tracking-[0.2em] uppercase text-valencia mb-2">{heading}</p>
          <h2 className="font-display text-3xl md:text-4xl font-bold text-foreground">{title}</h2>
          <p className="text-muted-foreground mt-3 max-w-2xl mx-auto">{subtitle}</p>
        </div>

        <div className="grid md:grid-cols-2 gap-6 mb-8">
          <motion.div variants={fadeUpItem} className="bg-card rounded-xl p-6 border border-border">
            <h3 className="font-display text-lg font-semibold text-foreground mb-3">{cycleTitle}</h3>
            <div className="space-y-3">
              {cycleSteps.map((item, i) => (
                <div key={i} className="flex gap-3 items-start">
                  <span className="shrink-0 w-7 h-7 rounded-full bg-valencia text-milk flex items-center justify-center font-display text-xs font-bold">
                    {item.step}
                  </span>
                  <div>
                    <p className="font-display text-sm font-semibold text-foreground">{item.title}</p>
                    <p className="text-muted-foreground text-xs">{item.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>

          <motion.div variants={fadeUpItem} className="bg-card rounded-xl p-6 border border-border">
            <h3 className="font-display text-lg font-semibold text-foreground mb-3">{timelineTitle}</h3>
            <div className="space-y-4">
              {timelinePhases.map((cycle, i) => (
                <div key={i} className="bg-muted rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-lg">{cycle.emoji}</span>
                    <span className="font-display text-sm font-bold text-foreground">{cycle.title}</span>
                    <span className="text-xs text-muted-foreground ml-auto font-display">{cycle.period}</span>
                  </div>
                  <ul className="space-y-1">
                    {cycle.items.map((item, j) => (
                      <li key={j} className="text-muted-foreground text-xs flex items-start gap-1.5">
                        <span className="text-valencia mt-0.5">•</span> {item}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </motion.div>
        </div>

        <div className="text-center">
          <Link to={linkHref} className="inline-flex items-center gap-2 font-display text-sm font-semibold text-primary hover:text-valencia transition-colors">
            {linkText}
          </Link>
        </div>
      </div>
    </motion.section>
  );
}
