import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { Award, BookOpen, CalendarDays, CheckCircle2, Clock, Lock, Sparkles } from "lucide-react";

import { PageShell, Reveal } from "@/components/page-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { usePlan } from "@/hooks/usePlan";
import { getCourseBySlug } from "@/lib/catalog.functions";
import { courseAccessLabel, isSponsoredCourse, requiresPro } from "@/lib/plans";

type Lesson = { title: string; body?: string; summary?: string };

export const Route = createFileRoute("/courses/$slug")({
  loader: async ({ params }) => {
    const course = await getCourseBySlug({ data: { slug: params.slug } });
    if (!course) throw notFound();
    return { course };
  },
  head: ({ loaderData }) => {
    if (!loaderData) {
      return {
        meta: [
          { title: "Course unavailable | UZIA Academy" },
          { name: "robots", content: "noindex" },
        ],
      };
    }
    const { title, summary } = loaderData.course;
    return {
      meta: [
        { title: `${title} | UZIA Academy` },
        { name: "description", content: summary },
        { property: "og:title", content: `${title} | UZIA Academy` },
        { property: "og:description", content: summary },
      ],
    };
  },
  notFoundComponent: CourseNotFound,
  errorComponent: CourseNotFound,
  component: CourseDetail,
});

function CourseNotFound() {
  return (
    <PageShell>
      <div className="mx-auto max-w-2xl px-4 py-24 text-center">
        <h1 className="text-3xl">We couldn't find that course</h1>
        <p className="mt-3 text-sm text-muted-foreground">
          It may have been renamed or removed from the catalogue.
        </p>
        <Button asChild className="mt-6 rounded-full">
          <Link to="/courses">Back to all courses</Link>
        </Button>
      </div>
    </PageShell>
  );
}

function CourseDetail() {
  const { course } = Route.useLoaderData();
  const { isPro } = usePlan();
  const locked = requiresPro(course) && !isPro;
  const lessons: Lesson[] = Array.isArray(course.lessons) ? (course.lessons as Lesson[]) : [];
  const outcomes: string[] = Array.isArray(course.learning_outcomes)
    ? (course.learning_outcomes as string[])
    : [];

  return (
    <PageShell>
      <div className="relative overflow-hidden bg-sunset text-primary-foreground">
        <div className="motif-chevron absolute inset-0 opacity-25" aria-hidden />
        <div className="relative mx-auto w-full max-w-4xl px-4 py-16">
          <div className="flex flex-wrap items-center gap-2">
            <Badge className="bg-white/15 text-primary-foreground">
              {course.group_code} · {course.group_name}
            </Badge>
            <Badge className="bg-gold text-gold-foreground">
              <Award className="mr-1 size-3" /> {course.credential_level}
            </Badge>
            <Badge variant="outline" className="border-white/40 text-primary-foreground">
              {course.domain_code}
            </Badge>
            {isSponsoredCourse(course) ? (
              <Badge className="bg-primary text-primary-foreground">
                <Sparkles className="mr-1 size-3" /> Fully sponsored
              </Badge>
            ) : null}
          </div>
          <h1 className="mt-5 text-4xl sm:text-5xl">{course.title}</h1>
          <p className="mt-5 max-w-2xl opacity-90">{course.summary}</p>
          <div className="mt-7 flex flex-wrap items-center gap-6 text-sm opacity-90">
            <span className="flex items-center gap-1.5">
              <CalendarDays className="size-4" /> {course.duration_weeks} weeks
            </span>
            <span className="flex items-center gap-1.5">
              <Clock className="size-4" /> {course.learning_hours} learning hours
            </span>
            <span className="flex items-center gap-1.5">
              <BookOpen className="size-4" /> {lessons.length} modules
            </span>
          </div>
          <p className="mt-7 font-display text-3xl font-extrabold text-gold">
            {courseAccessLabel(course)}
          </p>
          {locked ? (
            <>
              <Button
                asChild
                size="lg"
                className="mt-6 rounded-full bg-gold text-gold-foreground shadow-warm hover:bg-gold/90"
              >
                <Link to="/pricing">
                  <Lock className="mr-2 size-4" /> Unlock with a Pro plan
                </Link>
              </Button>
              <p className="mt-2 text-xs opacity-80">
                Foundation courses are fully sponsored. This programme is part of the Pro catalogue.
              </p>
            </>
          ) : (
            <>
              <Button
                asChild
                size="lg"
                className="mt-6 rounded-full bg-gold text-gold-foreground shadow-warm hover:bg-gold/90"
              >
                <Link to="/learn/$slug" params={{ slug: course.slug }}>
                  Enrol and start learning
                </Link>
              </Button>
              <p className="mt-2 text-xs opacity-80">
                Sign in required to track progress and claim your certificate.
              </p>
            </>
          )}
        </div>
        <div className="motif-divider" />
      </div>

      <section className="mx-auto w-full max-w-4xl px-4 py-16">
        <Reveal>
          <h2 className="text-2xl">About this programme</h2>
          <p className="mt-4 text-muted-foreground">{course.description}</p>
        </Reveal>

        {outcomes.length ? (
          <Reveal delay={0.08}>
            <h2 className="mt-14 text-2xl">What you'll be able to do</h2>
            <ul className="mt-5 grid gap-3 sm:grid-cols-2">
              {outcomes.map((o) => (
                <li key={o} className="flex gap-2.5 rounded-2xl border border-border bg-card p-4">
                  <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-primary" />
                  <span className="text-sm text-muted-foreground">{o}</span>
                </li>
              ))}
            </ul>
          </Reveal>
        ) : null}

        <Reveal delay={0.12}>
          <h2 className="mt-14 text-2xl">Weekly modules</h2>
          {locked ? (
            <div className="mt-5 rounded-2xl border border-border bg-surface p-5 text-sm text-muted-foreground">
              <Lock className="mb-2 size-4 text-primary" />
              The weekly module plan unlocks with a Pro plan.{" "}
              <Link to="/pricing" className="font-semibold text-primary underline-offset-4 hover:underline">
                See plans
              </Link>
            </div>
          ) : null}
          <ol className={locked ? "pointer-events-none mt-5 space-y-3 select-none blur-sm" : "mt-5 space-y-3"}>
            {lessons.map((lesson, i) => (
              <li
                key={lesson.title}
                className="flex gap-4 rounded-2xl border border-border bg-card p-5"
              >
                <span className="grid size-9 shrink-0 place-items-center rounded-xl bg-ember font-display text-sm font-bold text-primary-foreground">
                  {i + 1}
                </span>
                <div>
                  <p className="font-semibold">{lesson.title}</p>
                  {lesson.body ?? lesson.summary ? (
                    <p className="mt-1 text-sm text-muted-foreground">
                      {lesson.body ?? lesson.summary}
                    </p>
                  ) : null}
                </div>
              </li>
            ))}
          </ol>
        </Reveal>

        <Reveal delay={0.16}>
          <div className="mt-14 rounded-3xl border border-border bg-surface p-8">
            <Award className="size-7 text-primary" />
            <h2 className="mt-4 text-xl">{course.certificate_type}</h2>
            <p className="mt-2 text-sm text-muted-foreground">
              Complete every weekly module to claim a {course.credential_level}-level UZIA
              certificate with a unique number that anyone can verify publicly.
            </p>
          </div>
        </Reveal>
      </section>
    </PageShell>
  );
}
