import { motion } from "framer-motion";
import type { Course } from "@/data/curriculum";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";

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

/** Matches the previous decorative midpoint of the 40–85 random range. */
export const DEFAULT_COURSE_PROGRESS = 60;

interface CourseCardProps {
  course: Course;
  accentColor: "moss" | "deep-sea" | "valencia" | "sunflower";
}

function resolveProgress(course: Course): number {
  const raw = course.progress;
  const n = typeof raw === "number" ? raw : parseInt(String(raw ?? ""), 10);
  if (!Number.isFinite(n)) return DEFAULT_COURSE_PROGRESS;
  return Math.min(100, Math.max(0, n));
}

function resolveProgressColor(course: Course): string | null {
  const fromSnake = typeof course.progress_color === "string" ? course.progress_color.trim() : "";
  const fromCamel =
    typeof (course as Course & { progressColor?: string }).progressColor === "string"
      ? String((course as Course & { progressColor?: string }).progressColor).trim()
      : "";
  const hex = fromSnake || fromCamel;
  if (hex && /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/.test(hex)) return hex;
  return null;
}

export const CourseCard = ({ course, accentColor }: CourseCardProps) => {
  const visualProgress = resolveProgress(course);
  const customColor = resolveProgressColor(course);

  return (
    <Dialog>
      <DialogTrigger asChild>
        <motion.button
          whileHover={{ y: -4, scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
          transition={{ type: "spring", stiffness: 400, damping: 20 }}
          className="bg-card rounded-xl border border-border p-5 text-left w-full group cursor-pointer shadow-sm hover:shadow-md hover:border-primary/30 transition-[box-shadow,border-color] duration-300"
        >
          <div className="flex items-center gap-3 mb-3">
            <motion.span
              className="text-2xl"
              whileHover={{ rotate: [0, -10, 10, 0] }}
              transition={{ duration: 0.4 }}
            >
              {course.emoji}
            </motion.span>
            <div>
              <h3 className="font-display text-sm font-semibold text-foreground group-hover:text-primary transition-colors">{course.name}</h3>
              <span className={`inline-block text-[10px] font-display uppercase tracking-wider px-2 py-0.5 rounded-full ${course.type === "core" ? "bg-mist/30 text-deep-sea" : `${accentBg[accentColor]}/10 text-foreground`}`}>
                {course.type === "core" ? "Core · Year-long" : "DNA · 9 weeks"}
              </span>
            </div>
          </div>
          <p className="text-muted-foreground text-xs line-clamp-3 mb-3">{course.whatLearning}</p>
          <div className="flex items-center gap-2">
            <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
              <motion.div
                className={`h-full rounded-full ${customColor ? "" : accentBg[accentColor]}`}
                style={customColor ? { backgroundColor: customColor } : undefined}
                initial={{ width: 0 }}
                whileInView={{ width: `${visualProgress}%` }}
                viewport={{ once: true }}
                transition={{ duration: 0.8, delay: 0.2 }}
              />
            </div>
            <span className="text-[10px] text-muted-foreground font-display">{visualProgress}%</span>
          </div>
        </motion.button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto bg-card">
        <DialogHeader>
          <DialogTitle className="font-display text-xl flex items-center gap-3">
            <span className="text-3xl">{course.emoji}</span> {course.name}
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-6 mt-4">
          {course.bigIdea && (
            <div className="bg-muted/50 rounded-lg p-4 border border-border/50">
              <h4 className="font-display text-xs tracking-[0.15em] uppercase text-muted-foreground mb-1">Big Idea</h4>
              <p className="text-foreground text-sm leading-relaxed font-medium">{course.bigIdea}</p>
            </div>
          )}
          {course.courseEssentialQuestion && (
            <div className="bg-muted/50 rounded-lg p-4 border border-border/50">
              <h4 className="font-display text-xs tracking-[0.15em] uppercase text-muted-foreground mb-1">Essential Question</h4>
              <p className="text-foreground text-sm leading-relaxed italic">"{course.courseEssentialQuestion}"</p>
            </div>
          )}
          {course.courseNarrative && (
            <div>
              <h4 className="font-display text-sm font-semibold text-foreground mb-1">Course Narrative</h4>
              <p className="text-muted-foreground text-sm leading-relaxed">{course.courseNarrative}</p>
            </div>
          )}
          <div>
            <h4 className="font-display text-sm font-semibold text-foreground mb-1">What Your Child Is Learning</h4>
            <p className="text-muted-foreground text-sm leading-relaxed">{course.whatLearning}</p>
          </div>
          <div>
            <h4 className="font-display text-sm font-semibold text-foreground mb-1">How This Builds Toward Assessment</h4>
            <p className="text-muted-foreground text-sm leading-relaxed">{course.howBuilds}</p>
          </div>
          <div>
            <h4 className="font-display text-sm font-semibold text-foreground mb-2">Key Skills</h4>
            <div className="flex flex-wrap gap-2">
              {course.keySkills.map((skill) => (
                <motion.span
                  key={skill}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  className="bg-muted text-foreground text-xs px-3 py-1 rounded-full font-display"
                >
                  {skill}
                </motion.span>
              ))}
            </div>
          </div>
          <div>
            <h4 className="font-display text-sm font-semibold text-foreground mb-2">Standards</h4>
            <p className="text-muted-foreground text-xs">{course.standards.join(" · ")}</p>
          </div>
          <div>
            <h4 className="font-display text-sm font-semibold text-foreground mb-2">Portfolio Evidence</h4>
            <ul className="space-y-1">
              {course.portfolio.map((item) => (
                <li key={item} className="text-muted-foreground text-sm flex items-start gap-2">
                  <span className="text-valencia mt-1">•</span> {item}
                </li>
              ))}
            </ul>
          </div>
          <div className="bg-muted rounded-lg p-4">
            <h4 className="font-display text-sm font-semibold text-foreground mb-2">💬 Questions to Ask at Home</h4>
            <ul className="space-y-2">
              {course.questionsAtHome.map((q) => (
                <li key={q} className="text-foreground text-sm italic">"{q}"</li>
              ))}
            </ul>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
