import { Link } from "react-router-dom";
import { motion } from "framer-motion";
import { staggerContainer, fadeUpItem } from "@/components/PageTransition";
import { getDnaCourses } from "@/data/courseOverviews";

type Content = Record<string, unknown>;

export interface DnaCourseItem {
  name: string;
  emoji: string;
  duration: string;
  slug: string;
  linkText?: string;
  linkHref?: string;
}

export interface DnaStrandItem {
  name: string;
  courses: DnaCourseItem[];
}

const defaultHeading = "4 DNA Strands · 16 Rotating Courses";
const defaultTitle = "Specialty Skills That Rotate Every Quarter";
const defaultSubtitle = "Each strand delivers a progressive 4-course sequence across the year.";
const DEFAULT_STRAND_NAMES = ["Human Skills", "Human Science", "Design & Arts", "CT & Engineering"];

function parseStrands(content: Content | undefined): DnaStrandItem[] {
  const raw = content?.strands;
  if (!Array.isArray(raw) || raw.length === 0) {
    const dna = getDnaCourses();
    return DEFAULT_STRAND_NAMES.map((strandName) => ({
      name: strandName,
      courses: dna
        .filter((c) => c.strand === strandName)
        .map((c) => ({
          name: c.name,
          emoji: c.emoji,
          duration: c.duration,
          slug: c.slug,
          linkText: undefined,
          linkHref: undefined,
        })),
    })).filter((s) => s.courses.length > 0);
  }
  return raw
    .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
    .map((o) => {
      const rawCourses = o.courses;
      const courses: DnaCourseItem[] = Array.isArray(rawCourses)
        ? rawCourses
            .filter((x): x is Record<string, unknown> => x != null && typeof x === "object")
            .map((co) => ({
              name: typeof co.name === "string" ? co.name : "",
              emoji: typeof co.emoji === "string" ? co.emoji : "•",
              duration: typeof co.duration === "string" ? co.duration : "",
              slug: typeof co.slug === "string" ? co.slug : "#",
              linkText: typeof co.linkText === "string" ? co.linkText : undefined,
              linkHref: typeof co.linkHref === "string" ? co.linkHref : undefined,
            }))
            .filter((c) => c.name || c.slug !== "#")
        : [];
      return {
        name: typeof o.name === "string" ? o.name : "",
        courses,
      };
    })
    .filter((s) => s.name || s.courses.length > 0);
}

export function DnaStrandsBlock({ 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 strands = parseStrands(content);

  return (
    <section className="py-16 md:py-24 bg-background">
      <div className="container mx-auto px-6">
        <motion.div
          className="text-center mt-16 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-valencia mb-2">
            {heading}
          </p>
          <h2 className="font-display text-2xl md:text-3xl font-bold text-foreground">
            {title}
          </h2>
          <p className="text-muted-foreground mt-3 max-w-2xl mx-auto">
            {subtitle}
          </p>
        </motion.div>
        {strands.map((strand) => (
          <div key={strand.name} className="mb-8 max-w-4xl mx-auto">
            <p className="font-display text-xs tracking-[0.15em] uppercase text-muted-foreground mb-3">
              {strand.name}
            </p>
            <motion.div
              className="grid grid-cols-2 sm:grid-cols-4 gap-3"
              variants={staggerContainer}
              initial="initial"
              whileInView="animate"
              viewport={{ once: true, margin: "-50px" }}
            >
              {strand.courses.map((course, idx) => {
                const href = course.linkHref?.trim() || `/course/${course.slug}`;
                const linkLabel = course.linkText?.trim() || "Learn More →";
                const isExternal = href.startsWith("http://") || href.startsWith("https://");
                const linkClass =
                  "group block bg-card rounded-xl p-4 border border-border hover:border-accent/30 transition-all hover:shadow-lg text-center";
                const inner = (
                  <>
                    <motion.span
                      className="text-2xl block mb-1"
                      whileHover={{ rotate: [0, -10, 10, 0] }}
                      transition={{ duration: 0.4 }}
                    >
                      {course.emoji}
                    </motion.span>
                    <h3 className="font-display text-xs font-bold text-foreground mb-0.5">
                      {course.name}
                    </h3>
                    <p className="text-muted-foreground text-[0.65rem]">
                      {course.duration ? course.duration.replace("9 Weeks ", "") : ""}
                    </p>
                    <span className="font-display text-[0.65rem] text-valencia font-semibold mt-1 block group-hover:translate-x-1 transition-transform">
                      {linkLabel}
                    </span>
                  </>
                );
                return (
                  <motion.div
                    key={`${course.slug}-${idx}`}
                    variants={fadeUpItem}
                    whileHover={{ y: -4 }}
                    transition={{ type: "spring", stiffness: 400, damping: 20 }}
                  >
                    {isExternal ? (
                      <a
                        href={href}
                        className={linkClass}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {inner}
                      </a>
                    ) : (
                      <Link to={href} className={linkClass}>
                        {inner}
                      </Link>
                    )}
                  </motion.div>
                );
              })}
            </motion.div>
          </div>
        ))}
      </div>
    </section>
  );
}
