import { useParams } from "react-router-dom";
import { motion } from "framer-motion";
import { useState } from "react";
import { PageTransition } from "@/components/PageTransition";
import { GradeHeroBlock } from "@/components/page-blocks";

interface Competition {
  name: string;
  publicCompetition?: string;
  publicTiming?: string;
  orionPrepTiming?: string;
  orionMonth?: string;
  dateTime?: string;
  method?: string;
  description?: string;
  committee: string;
  emoji: string;
  color: string;
}

const monthTimeline = [
  "August", "September", "October", "November", "December",
  "January", "February", "March", "April", "May", "June",
];

function getMonthBucket(month?: string): string | null {
  if (!month) return null;
  const t = month.toLowerCase();
  for (const m of monthTimeline) {
    if (t.includes(m.toLowerCase())) return m;
  }
  return null;
}

const rawData = [
  { committee: "Writing & Literature", emoji: "✍️", color: "deep-sea", competitions: [
    { name: "Creative Writing Contest", publicCompetition: "Scholastic Art & Writing Awards", publicTiming: "December–January", orionPrepTiming: "November", orionMonth: "November", dateTime: "Third Monday of the month", method: "Submission" },
  ]},
  { committee: "Advocacy & Change Makers", emoji: "✊", color: "valencia", competitions: [
    { name: "Future City Project", publicCompetition: "Future City Competition", publicTiming: "January", orionPrepTiming: "Early Fall to December", orionMonth: "May", dateTime: "Weekdays (9–12)", method: "Weekdays (9–12)" },
    { name: "Environment Awareness Video", publicCompetition: "World of 7 Billion Video Contest", publicTiming: "February", orionPrepTiming: "January", orionMonth: "January", dateTime: "Third Monday of the month", method: "Submission" },
  ]},
  { committee: "Thrive & Lead", emoji: "🌟", color: "moss", competitions: [
    { name: "Innovation Convention", description: "Entrepreneurship contests" },
    { name: "TREP$", description: "A project-based learning program that teaches kids how to start their own businesses in a fun, experiential way. They often hold fairs and competitions.", publicTiming: "Varies", orionPrepTiming: "1–2 months before" },
    { name: "TiE Young Entrepreneurs (TYE)", description: "A global program fostering future generations of entrepreneurs. Students learn business basics and teamwork, culminating in business plan competitions.", publicTiming: "Spring", orionPrepTiming: "Late Winter or Early Spring" },
  ]},
  { committee: "STEM Innovation & Entrepreneurship", emoji: "🚀", color: "sunflower", competitions: [
    { name: "National Youth Entrepreneurship Challenge", description: "Offered by NFTE for students who have completed one of their programs.", publicTiming: "Fall", orionPrepTiming: "Late Summer or Early Fall" },
    { name: "Biz Kid$ Business Plan Competition", description: "Submit business plans for a chance to win money to support your business idea.", publicTiming: "Fall", orionPrepTiming: "Late Summer or Early Fall" },
    { name: "Classroom Market Day", orionMonth: "January", dateTime: "Third Saturday of the month", method: "Saturday (9–1)" },
    { name: "Entrepreneurship World Cup", description: "Category for school-aged children (up to 15) to share innovative ideas.", publicTiming: "Fall", orionPrepTiming: "Late Summer or Early Fall", orionMonth: "May", dateTime: "Second Wednesday of the month", method: "School Time in classrooms" },
    { name: "Robotics Competition", publicCompetition: "FIRST LEGO League / FIRST LEGO League Jr.", publicTiming: "Late Fall–Winter", orionPrepTiming: "Beginning of School Year", orionMonth: "September", dateTime: "Second Thursdays", method: "Weekdays After School" },
    { name: "STEM Fair", publicCompetition: "SIBA STEM Competitions", publicTiming: "November", orionPrepTiming: "October", orionMonth: "November", dateTime: "Second Thursdays", method: "Weekdays After School" },
    { name: "Math Olympiad Day", publicCompetition: "AMC 8 (Middle School)", publicTiming: "November", orionPrepTiming: "October", orionMonth: "October", dateTime: "Second Thursdays", method: "Weekdays After School" },
    { name: "Bridge Building Competition", publicCompetition: "West Point Bridge Design Contest", publicTiming: "May", orionPrepTiming: "April", orionMonth: "March", dateTime: "Second Thursdays", method: "Weekdays After School" },
  ]},
  { committee: "Artistic Endeavors", emoji: "🎨", color: "valencia", competitions: [
    { name: "Arts Competition", publicCompetition: "Congressional Art Competition, Doodle for Google, or International Children's Painting Competition", publicTiming: "Spring", orionPrepTiming: "Late Winter", orionMonth: "February", dateTime: "Third Monday of the month", method: "Submission" },
  ]},
  { committee: "Leisure and Learning", emoji: "♟️", color: "deep-sea", competitions: [
    { name: "Doodle for Google", publicTiming: "Spring", orionPrepTiming: "Late Winter", orionMonth: "February" },
    { name: "International Children's Painting Competition", publicTiming: "Spring", orionPrepTiming: "Late Winter", orionMonth: "February" },
  ]},
  { committee: "Sports", emoji: "⚽", color: "mist", competitions: [
    { name: "Chess Championship", publicCompetition: "U.S. Chess Federation Tournaments", publicTiming: "Year-round", orionPrepTiming: "Mid-school year", orionMonth: "December", dateTime: "Second Thursdays", method: "After School Club Time" },
  ]},
  { committee: "Parent Engagement", emoji: "🤝", color: "salmon", competitions: [
    { name: "Career Fair", publicCompetition: "NCDA's Poetry and Poster Contest", publicTiming: "April", orionPrepTiming: "March", orionMonth: "September, March", dateTime: "Weekdays (9–2)", method: "Weekdays (9–2)" },
    { name: "Diversity Night", orionMonth: "April", dateTime: "5:30 pm to 8:30 pm" },
    { name: "Astronomy Night", orionMonth: "November", dateTime: "6 pm to 7:30 pm" },
    { name: "Family Money Night" },
  ]},
];

const allCompetitions: Competition[] = rawData.flatMap(group =>
  group.competitions.map(c => ({ ...c, committee: group.committee, emoji: group.emoji, color: group.color }))
);

// Orion tab: competitions with an orionMonth
const orionComps = allCompetitions.filter(c => c.orionMonth);
// Public tab: competitions with publicTiming or publicCompetition but no orionMonth
const publicComps = allCompetitions.filter(c => !c.orionMonth && (c.publicTiming || c.publicCompetition));
const flexibleComps = allCompetitions.filter(c => !c.orionMonth && !c.publicTiming && !c.publicCompetition);

type MonthGroup = { month: string; comps: Competition[] };

function groupByMonth(comps: Competition[], useOrionMonth: boolean): MonthGroup[] {
  const groups: Record<string, Competition[]> = {};
  for (const c of comps) {
    const field = useOrionMonth ? c.orionMonth : c.publicTiming;
    if (!field) continue;
    // Handle multi-month like "September, March"
    const months = field.split(",").map(s => s.trim());
    for (const m of months) {
      const bucket = getMonthBucket(m);
      if (!bucket) continue;
      if (!groups[bucket]) groups[bucket] = [];
      groups[bucket].push(c);
    }
  }
  return monthTimeline
    .filter(m => groups[m])
    .map(m => ({ month: m, comps: groups[m] }));
}

const orionTimeline = groupByMonth(orionComps, true);
const publicTimeline = groupByMonth(publicComps, false);

const colorMap: Record<string, string> = {
  "deep-sea": "border-deep-sea bg-deep-sea/10",
  "valencia": "border-valencia bg-valencia/10",
  "moss": "border-moss bg-moss/10",
  "sunflower": "border-sunflower bg-sunflower/10",
  "salmon": "border-salmon bg-salmon/10",
  "mist": "border-mist bg-mist/10",
};
const dotMap: Record<string, string> = {
  "deep-sea": "bg-deep-sea", "valencia": "bg-valencia", "moss": "bg-moss",
  "sunflower": "bg-sunflower", "salmon": "bg-salmon", "mist": "bg-mist",
};

const gradeLabels: Record<string, string> = {
  kg: "Kindergarten", "1": "Grade 1", "2": "Grade 2", "3": "Grade 3", "4": "Grade 4", "5": "Grade 5",
};

const CompCard = ({ comp }: { comp: Competition }) => (
  <div className={`rounded-xl border-l-4 ${colorMap[comp.color]} bg-card p-4 shadow-sm hover:shadow-md transition-shadow`}>
    <div className="flex items-center gap-2 mb-1">
      <span className="text-base">{comp.emoji}</span>
      <h3 className="font-display text-sm font-bold text-foreground">{comp.name}</h3>
    </div>
    <p className="text-[0.65rem] text-muted-foreground font-display mb-1.5">{comp.committee}</p>
    {comp.description && <p className="text-xs text-muted-foreground leading-relaxed mb-2">{comp.description}</p>}
    {comp.publicCompetition && (
      <p className="text-xs text-foreground/80 mb-1.5"><span className="text-muted-foreground">Public: </span>{comp.publicCompetition}</p>
    )}
    <div className="flex flex-wrap gap-1.5 mt-2">
      {comp.publicTiming && <span className="text-[0.6rem] bg-muted text-muted-foreground px-2 py-0.5 rounded-full font-display">📅 Public: {comp.publicTiming}</span>}
      {comp.orionMonth && <span className="text-[0.6rem] bg-primary/10 text-primary px-2 py-0.5 rounded-full font-display">🏫 Orion: {comp.orionMonth}</span>}
      {comp.dateTime && <span className="text-[0.6rem] bg-muted text-muted-foreground px-2 py-0.5 rounded-full font-display">🕐 {comp.dateTime}</span>}
      {comp.method && <span className="text-[0.6rem] bg-muted text-muted-foreground px-2 py-0.5 rounded-full font-display">📋 {comp.method}</span>}
    </div>
  </div>
);

const TimelineSection = ({ title, emoji, timeline, accentClass }: { title: string; emoji: string; timeline: MonthGroup[]; accentClass: string }) => (
  <div>
    <div className="flex items-center gap-3 mb-8 justify-center">
      <div className="h-px flex-1 bg-border" />
      <span className={`font-display text-lg font-bold ${accentClass}`}>{emoji} {title}</span>
      <div className="h-px flex-1 bg-border" />
    </div>
    <div className="relative">
      {/* Spine */}
      <div className="absolute left-6 md:left-1/2 top-0 bottom-0 w-0.5 bg-border md:-translate-x-1/2" />

      <div className="flex flex-col gap-10">
        {timeline.map((group, gi) => (
          <div key={group.month} className="relative">
            {/* Month marker */}
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              className="relative z-10 flex md:justify-center mb-4"
            >
              <div className="ml-1 md:ml-0">
                <span className={`inline-block font-display text-xs font-bold px-3 py-1 rounded-full border ${accentClass} bg-background`}>
                  {group.month}
                </span>
              </div>
            </motion.div>

            {/* Cards for this month */}
            <div className="flex flex-col gap-4">
              {group.comps.map((comp, ci) => {
                const side = (gi + ci) % 2 === 0 ? "left" : "right";
                return (
                  <div key={comp.name + ci} className="relative">
                    {/* Desktop alternating */}
                    <div className="hidden md:flex w-full items-start">
                      {side === "left" ? (
                        <>
                          <motion.div
                            className="w-[calc(50%-1.5rem)] flex justify-end"
                            initial={{ opacity: 0, x: -20 }}
                            whileInView={{ opacity: 1, x: 0 }}
                            viewport={{ once: true }}
                            transition={{ delay: ci * 0.05 }}
                          >
                            <div className="max-w-sm w-full"><CompCard comp={comp} /></div>
                          </motion.div>
                          <div className="w-12 flex justify-center relative z-10 pt-4">
                            <div className={`w-3 h-3 rounded-full ${dotMap[comp.color]} border-2 border-background`} />
                          </div>
                          <div className="w-[calc(50%-1.5rem)]" />
                        </>
                      ) : (
                        <>
                          <div className="w-[calc(50%-1.5rem)]" />
                          <div className="w-12 flex justify-center relative z-10 pt-4">
                            <div className={`w-3 h-3 rounded-full ${dotMap[comp.color]} border-2 border-background`} />
                          </div>
                          <motion.div
                            className="w-[calc(50%-1.5rem)] flex justify-start"
                            initial={{ opacity: 0, x: 20 }}
                            whileInView={{ opacity: 1, x: 0 }}
                            viewport={{ once: true }}
                            transition={{ delay: ci * 0.05 }}
                          >
                            <div className="max-w-sm w-full"><CompCard comp={comp} /></div>
                          </motion.div>
                        </>
                      )}
                    </div>
                    {/* Mobile */}
                    <motion.div
                      className="md:hidden flex items-start"
                      initial={{ opacity: 0, x: 15 }}
                      whileInView={{ opacity: 1, x: 0 }}
                      viewport={{ once: true }}
                    >
                      <div className="w-12 flex justify-center relative z-10 pt-4">
                        <div className={`w-3 h-3 rounded-full ${dotMap[comp.color]} border-2 border-background`} />
                      </div>
                      <div className="flex-1"><CompCard comp={comp} /></div>
                    </motion.div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

const CompetitionsPage = () => {
  const { grade } = useParams<{ grade: string }>();
  const gradeKey = grade || "kg";
  const gradeLabel = gradeLabels[gradeKey] || `Grade ${gradeKey}`;
  const [tab, setTab] = useState<"orion" | "public">("orion");

  return (
    <PageTransition>
      <div className="min-h-screen bg-background">
        <GradeHeroBlock
          activeButtonId={tab}
          onButtonClick={(button) => setTab(button.id === "public" ? "public" : "orion")}
          content={{
            layout: "detail",
            showLogo: false,
            backLabel: "Back to Kaleidoscope",
            backHref: `/grade/${gradeKey}`,
            mainIcon: "🏆",
            title: "Competitions Timeline",
            subtitle: `${gradeLabel} · August – June`,
            buttons: [
              { id: "orion", icon: "🏫", label: `Orion Competitions (${orionComps.length})`, href: "" },
              { id: "public", icon: "🌍", label: `Public Competitions (${publicComps.length + flexibleComps.length})`, href: "" },
            ],
            backgroundPattern: "radial",
            accentColor: "sunflower",
            patternPosition: "70% 40%",
          }}
        />

        <section className="py-16 bg-background">
          <div className="container mx-auto px-6 max-w-4xl">
            {tab === "orion" ? (
              <TimelineSection title="Orion Competitions" emoji="🏫" timeline={orionTimeline} accentClass="text-primary border-primary" />
            ) : (
              <>
                <TimelineSection title="Public Competitions" emoji="🌍" timeline={publicTimeline} accentClass="text-valencia border-valencia" />
                {flexibleComps.length > 0 && (
                  <div className="mt-16">
                    <div className="flex items-center gap-3 mb-6 justify-center">
                      <div className="h-px flex-1 bg-border" />
                      <span className="font-display text-sm font-bold text-muted-foreground">📌 Flexible / Ongoing</span>
                      <div className="h-px flex-1 bg-border" />
                    </div>
                    <div className="grid sm:grid-cols-2 gap-4 max-w-2xl mx-auto">
                      {flexibleComps.map((comp, i) => (
                        <motion.div key={comp.name} initial={{ opacity: 0, y: 15 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ delay: i * 0.05 }}>
                          <CompCard comp={comp} />
                        </motion.div>
                      ))}
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </section>

      </div>
    </PageTransition>
  );
};

export default CompetitionsPage;
