import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";

import { CourseCard } from "@/components/course-card";
import { PageHeader, PageShell, Reveal } from "@/components/page-shell";
import { Button } from "@/components/ui/button";
import { usePlan } from "@/hooks/usePlan";
import { listCategories, listCourses } from "@/lib/catalog.functions";

export const Route = createFileRoute("/courses/")({
  head: () => ({
    meta: [
      { title: "50 MSME Courses — Finance, Digital, Market Access | UZIA Academy" },
      {
        name: "description",
        content:
          "The full UZIA Academy catalogue: 50 applied courses across entrepreneurship, finance, marketing, digital and AI, analytics, operations, people, governance, market access and scale.",
      },
      { property: "og:title", content: "UZIA Academy course catalogue" },
      {
        property: "og:description",
        content: "50 applied business courses built for African micro, small and medium enterprises.",
      },
    ],
  }),
  loader: async () => ({
    courses: await listCourses(),
    categories: await listCategories(),
  }),
  component: CoursesPage,
});

const CREDENTIALS = ["Foundation", "Professional", "Growth", "Advanced", "Executive", "Mastery"];

function CoursesPage() {
  const { courses, categories } = Route.useLoaderData();
  const { isPro } = usePlan();
  const [group, setGroup] = useState<string>("all");
  const [credential, setCredential] = useState<string>("all");

  const groups = useMemo(() => {
    const map = new Map<string, string>();
    for (const c of courses) if (c.group_code) map.set(c.group_code, c.group_name);
    return [...map.entries()].sort(([a], [b]) => a.localeCompare(b));
  }, [courses]);

  const credentialsUsed = CREDENTIALS.filter((l) =>
    courses.some((c) => c.credential_level === l),
  );

  const visible = courses.filter(
    (c) =>
      (group === "all" || c.group_code === group) &&
      (credential === "all" || c.credential_level === credential),
  );

  return (
    <PageShell>
      <PageHeader
        eyebrow={`${courses.length} courses · 10 disciplines`}
        title="The UZIA Academy catalogue"
        description="Foundation programmes are fully sponsored for every learner. Every programme runs in applied weekly modules against your own business, priced in shillings, and ends in a UZIA credential. Take the assessment first for a sequenced pathway."
      />

      <section className="mx-auto w-full max-w-6xl px-4 py-14">
        <div className="space-y-4">
          <div>
            <p className="mb-2.5 text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">
              Discipline
            </p>
            <div className="flex flex-wrap gap-2">
              <Button
                size="sm"
                className="rounded-full"
                variant={group === "all" ? "default" : "outline"}
                onClick={() => setGroup("all")}
              >
                All disciplines
              </Button>
              {groups.map(([code, name]) => (
                <Button
                  key={code}
                  size="sm"
                  className="rounded-full"
                  variant={group === code ? "default" : "outline"}
                  onClick={() => setGroup(code)}
                >
                  {code} · {name}
                </Button>
              ))}
            </div>
          </div>

          <div>
            <p className="mb-2.5 text-xs font-semibold uppercase tracking-[0.2em] text-muted-foreground">
              Credential level
            </p>
            <div className="flex flex-wrap gap-2">
              <Button
                size="sm"
                className="rounded-full"
                variant={credential === "all" ? "default" : "outline"}
                onClick={() => setCredential("all")}
              >
                All levels
              </Button>
              {credentialsUsed.map((l) => (
                <Button
                  key={l}
                  size="sm"
                  className="rounded-full"
                  variant={credential === l ? "default" : "outline"}
                  onClick={() => setCredential(l)}
                >
                  {l}
                </Button>
              ))}
            </div>
          </div>
        </div>

        <p className="mt-8 text-sm text-muted-foreground">
          Showing {visible.length} of {courses.length} courses
        </p>

        <div className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {visible.map((course, i) => (
            <Reveal key={course.slug} delay={(i % 3) * 0.06}>
              <CourseCard
                course={course}
                isPro={isPro}
                categoryName={categories.find((c) => c.slug === course.category_slug)?.name}
              />
            </Reveal>
          ))}
        </div>
      </section>
    </PageShell>
  );
}
