import { Link } from "react-router-dom";
import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import { quarters as defaultQuarters } from "@/data/curriculum";

type Content = Record<string, unknown>;

const QUARTER_COLORS = {
  moss: "bg-moss",
  "deep-sea": "bg-deep-sea",
  valencia: "bg-valencia",
  sunflower: "bg-sunflower",
} as const;

const QUARTER_BORDER_COLORS = {
  moss: "border-moss",
  "deep-sea": "border-deep-sea",
  valencia: "border-valencia",
  sunflower: "border-sunflower",
} as const;

export type YearAtGlanceQuarterItem = {
  id: number;
  color: "valencia" | "sunflower" | "deep-sea" | "moss";
  emoji: string;
  role: string;
  subtitle: string;
  title: string;
  essentialQuestion: string;
  theme: string;
  linkText?: string;
  linkHref?: string;
};

const defaultHeading = "The Year at a Glance";
const defaultTitle = "One Project. Four Roles. Infinite Growth.";

function parseQuarters(content: Content | undefined): YearAtGlanceQuarterItem[] {
  const raw = content?.quarters;
  if (!Array.isArray(raw) || raw.length === 0) {
    return defaultQuarters.map((q) => ({
      id: q.id,
      color: q.color,
      emoji: q.emoji,
      role: q.role,
      subtitle: q.subtitle,
      title: q.title,
      essentialQuestion: q.essentialQuestion,
      theme: q.theme,
      linkText: undefined,
      linkHref: undefined,
    }));
  }
  return raw
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => ({
      id: typeof o.id === "number" ? o.id : Number(o.id) || 1,
      color: (["valencia", "sunflower", "deep-sea", "moss"].includes(o.color as string) ? o.color : "moss") as YearAtGlanceQuarterItem["color"],
      emoji: typeof o.emoji === "string" ? o.emoji : "•",
      role: typeof o.role === "string" ? o.role : "",
      subtitle: typeof o.subtitle === "string" ? o.subtitle : "",
      title: typeof o.title === "string" ? o.title : "",
      essentialQuestion: typeof o.essentialQuestion === "string" ? o.essentialQuestion : "",
      theme: typeof o.theme === "string" ? o.theme : "",
      linkText: typeof o.linkText === "string" ? o.linkText : undefined,
      linkHref: typeof o.linkHref === "string" ? o.linkHref : undefined,
    }))
    .filter((q) => q.id != null);
}

export function YearAtGlanceBlock({ content }: { content?: Content }) {
  const heading = (content?.heading as string) ?? defaultHeading;
  const title = (content?.title as string) ?? defaultTitle;
  const quarters = parseQuarters(content);

  return (
    <section className="py-16 md:py-24 bg-background">
      <div className="container mx-auto px-6">
        <motion.div
          className="text-center mb-12"
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5 }}
        >
          <p className="font-display text-xs tracking-[0.2em] uppercase text-deep-sea mb-2">
            {heading}
          </p>
          <h2 className="font-display text-3xl md:text-4xl font-bold text-foreground">
            {title}
          </h2>
        </motion.div>
        <motion.div
          className="grid md:grid-cols-2 lg:grid-cols-4 gap-6"
          variants={staggerContainer}
          initial="initial"
          whileInView="animate"
          viewport={{ once: true, margin: "-80px" }}
        >
          {quarters.map((q) => {
            const href = q.linkHref?.trim() || `/quarter/${q.id}`;
            const linkLabel = q.linkText?.trim() || "Explore →";
            const isExternal = href.startsWith("http://") || href.startsWith("https://");
            const colorClass = QUARTER_COLORS[q.color] ?? QUARTER_COLORS.moss;
            const borderClass = QUARTER_BORDER_COLORS[q.color] ?? QUARTER_BORDER_COLORS.moss;
            const card = (
              <div className={`rounded-xl overflow-hidden border-2 ${borderClass} bg-card h-full flex flex-col`}>
                <div className={`${colorClass} p-6 text-center`}>
                  <span className="text-4xl block mb-2">{q.emoji}</span>
                  <span className="font-display text-xs tracking-widest uppercase text-milk/80">
                    Quarter {q.id}
                  </span>
                  <h3 className="font-display text-xl font-bold text-milk mt-1">{q.role}</h3>
                </div>
                <div className="p-5 flex-1 flex flex-col">
                  <p className="font-display text-sm font-semibold text-foreground mb-1">
                    {q.subtitle}: {q.title}
                  </p>
                  <p className="text-muted-foreground text-sm mb-3 flex-1">{q.essentialQuestion}</p>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground font-display">{q.theme}</span>
                    <span className="font-display text-xs text-deep-sea font-semibold group-hover:translate-x-1 transition-transform">
                      {linkLabel}
                    </span>
                  </div>
                </div>
              </div>
            );
            return (
              <motion.div key={q.id} variants={fadeUpItem}>
                {isExternal ? (
                  <a href={href} className="orion-card-hover group block h-full" target="_blank" rel="noopener noreferrer">
                    {card}
                  </a>
                ) : (
                  <Link to={href} className="orion-card-hover group block h-full">
                    {card}
                  </Link>
                )}
              </motion.div>
            );
          })}
        </motion.div>
      </div>
    </section>
  );
}
