import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { getPublishedCourseBySlug } from "@/lib/academy/queries";
import { getCourseDetailContent } from "@/lib/academy/course-detail";
import { auth } from "@/lib/auth/auth";
import { db } from "@/lib/db/client";
import { enrollments } from "@/lib/db/schema";
import { and, eq } from "drizzle-orm";
import { enrollInCourse } from "./actions";
import { siteConfig } from "@/lib/site-config";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const data = await getPublishedCourseBySlug(slug);
  if (!data) return { title: "Course not found" };
  return {
    title: `${data.course.title} · Academy`,
    description: data.course.shortDescription || undefined,
  };
}

export default async function AcademyCoursePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const data = await getPublishedCourseBySlug(slug);
  if (!data) notFound();

  const { course, modules, enrolledCount, totalLessons, totalDurationMin } = data;
  const detail = getCourseDetailContent(course.slug);
  const { listCourseResources } = await import("@/lib/academy/resources");
  const resources = await listCourseResources(course.id);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Course",
    name: course.title,
    description: course.description || course.shortDescription || undefined,
    url: `${siteConfig.url}/products/academy/courses/${course.slug}`,
    educationalLevel: course.level,
    about: course.topic,
    provider: {
      "@type": "Organization",
      name: `${siteConfig.name} Academy`,
      url: `${siteConfig.url}/products/academy`,
    },
    ...(course.instructorName
      ? {
          instructor: {
            "@type": "Person",
            name: course.instructorName,
            jobTitle: course.instructorTitle ?? undefined,
            description: course.instructorBio ?? undefined,
          },
        }
      : {}),
    hasCourseInstance: {
      "@type": "CourseInstance",
      courseMode: "onsite",
      courseWorkload: totalDurationMin > 0 ? `PT${totalDurationMin}M` : undefined,
    },
  };

  const session = await auth();
  const userId = (session?.user as { id?: string } | undefined)?.id;
  let isEnrolled = false;
  if (userId) {
    const [row] = await db
      .select({ userId: enrollments.userId })
      .from(enrollments)
      .where(and(eq(enrollments.courseId, course.id), eq(enrollments.userId, userId)))
      .limit(1);
    isEnrolled = Boolean(row);
  }

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <section className="relative overflow-hidden border-b border-[var(--color-line)] bg-gradient-to-b from-[var(--color-mist)]/60 to-white pb-10 pt-10 md:pb-14 md:pt-14">
        <Container>
          <div className="relative mx-auto max-w-5xl">
            <Breadcrumbs
              items={[
                { label: "Academy", href: "/products/academy" },
                { label: "Courses", href: "/products/academy/courses" },
                { label: course.title },
              ]}
            />

            <div className="mt-6 grid gap-10 md:grid-cols-[1.3fr_1fr] md:items-start">
              <div>
                <div className="flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                  <span>{course.level}</span>
                  <span className="text-[var(--color-line)]">·</span>
                  <span className="text-[var(--color-slate)]">{course.topic}</span>
                </div>
                <h1 className="mt-4 font-display text-[40px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)] md:text-[56px]">
                  {course.title}
                </h1>
                {course.shortDescription && (
                  <p className="mt-6 text-[19px] leading-[1.55] text-[var(--color-slate)]">
                    {course.shortDescription}
                  </p>
                )}
                <div className="mt-6 flex flex-wrap items-center gap-4 text-[14px] text-[var(--color-slate)]">
                  <span>{totalLessons} lesson{totalLessons === 1 ? "" : "s"}</span>
                  {totalDurationMin > 0 && (
                    <>
                      <span className="text-[var(--color-line)]">·</span>
                      <span>{totalDurationMin} min total</span>
                    </>
                  )}
                  <span className="text-[var(--color-line)]">·</span>
                  <span>{enrolledCount} enrolled</span>
                </div>
                <div className="mt-8 flex flex-wrap items-center gap-4">
                  {isEnrolled ? (
                    <Button href={`/account/academy/${course.id}`}>Continue course</Button>
                  ) : userId ? (
                    <form action={enrollInCourse}>
                      <input type="hidden" name="courseId" value={course.id} />
                      <Button type="submit">Enrol now</Button>
                    </form>
                  ) : (
                    <Button href={`/login?next=/products/academy/courses/${course.slug}`}>
                      Sign in to enrol
                    </Button>
                  )}
                  <Button href="/products/academy/courses" variant="ghost">
                    Back to catalogue
                  </Button>
                </div>
              </div>

              {course.coverPhoto && (
                <div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)] shadow-[0_30px_64px_rgba(10,14,40,0.10)]">
                  <Image
                    src={course.coverPhoto}
                    alt={course.coverPhotoAlt ?? course.title}
                    fill
                    sizes="(min-width: 1024px) 480px, 100vw"
                    className="object-cover"
                    priority
                  />
                </div>
              )}
            </div>
          </div>
        </Container>
      </section>

      <section className="border-b border-[var(--color-line)] bg-white py-16 md:py-20">
        <Container>
          <div className="mx-auto grid max-w-5xl gap-12 md:grid-cols-[1.4fr_1fr]">
            <div className="space-y-12">
              {(detail?.overview || course.description) && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Course overview
                  </h2>
                  <p className="mt-4 whitespace-pre-wrap text-[16px] leading-relaxed text-[var(--color-slate)]">
                    {detail?.overview || course.description}
                  </p>
                </div>
              )}

              {detail?.whoShouldAttend && detail.whoShouldAttend.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Who should attend
                  </h2>
                  <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-slate)]">
                    {detail.whoShouldAttend.map((audience, i) => (
                      <li key={i} className="flex gap-3">
                        <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
                        {audience}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {detail?.highlights && detail.highlights.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Course highlights
                  </h2>
                  <div className="mt-6 grid gap-4 sm:grid-cols-2">
                    {detail.highlights.map((h, i) => (
                      <div
                        key={i}
                        className="rounded-xl border border-[var(--color-line)] bg-white p-5"
                      >
                        <div className="font-display text-[16px] font-extrabold tracking-tight text-[var(--color-ink)]">
                          {h.title}
                        </div>
                        <p className="mt-2 text-[14px] leading-relaxed text-[var(--color-slate)]">
                          {h.body}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {detail?.programme && detail.programme.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Programme
                  </h2>
                  <ol className="mt-6 space-y-4">
                    {detail.programme.map((block, i) => (
                      <li
                        key={i}
                        className="overflow-hidden rounded-2xl border border-[var(--color-line)] bg-white"
                      >
                        <div className="flex flex-wrap items-center gap-3 border-b border-[var(--color-line)] bg-[var(--color-mist)]/40 px-5 py-3">
                          <span className="rounded-full bg-[var(--color-blue)] px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white">
                            {block.time}
                          </span>
                          {block.title && (
                            <span className="font-display text-[15px] font-extrabold tracking-tight text-[var(--color-ink)]">
                              {block.title}
                            </span>
                          )}
                        </div>
                        {block.items.length > 0 && (
                          <ul className="divide-y divide-[var(--color-line)]">
                            {block.items.map((item, j) => (
                              <li
                                key={j}
                                className="flex items-start gap-3 px-5 py-3 text-[14px] text-[var(--color-ink)]"
                              >
                                <span className="mt-1.5 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
                                {item}
                              </li>
                            ))}
                          </ul>
                        )}
                      </li>
                    ))}
                  </ol>
                </div>
              )}

              {detail?.whyDifferent && detail.whyDifferent.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Why this course is different
                  </h2>
                  <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-slate)]">
                    {detail.whyDifferent.map((note, i) => (
                      <li key={i} className="flex gap-3">
                        <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
                        {note}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {resources.length > 0 ? (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Resources
                  </h2>
                  <ul className="mt-6 grid gap-3 sm:grid-cols-2">
                    {resources.map((r) => (
                      <li
                        key={r.id}
                        className="rounded-2xl border border-[var(--color-line)] bg-white p-5 transition-colors hover:border-[var(--color-blue)]"
                      >
                        <div className="flex items-center justify-between gap-2 text-[11px] font-bold uppercase tracking-[0.12em] text-[var(--color-blue)]">
                          <span>{r.type.replace("_", " ")}</span>
                        </div>
                        <div className="mt-2 font-display text-[16px] font-extrabold leading-tight text-[var(--color-ink)]">
                          {r.title}
                        </div>
                        {r.description ? (
                          <p className="mt-1 line-clamp-3 text-[13px] leading-relaxed text-[var(--color-slate)]">
                            {r.description}
                          </p>
                        ) : null}
                        <a
                          href={r.url}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-3 inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
                        >
                          Open →
                        </a>
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}

              <div>
                <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                  Curriculum
                </h2>
                {modules.length === 0 ? (
                  <p className="mt-4 text-[15px] text-[var(--color-slate)]">
                    Curriculum coming soon.
                  </p>
                ) : (
                  <ol className="mt-6 space-y-4">
                    {modules.map((m, i) => (
                      <li
                        key={m.id}
                        className="rounded-2xl border border-[var(--color-line)] bg-white p-6"
                      >
                        <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                          Module {i + 1}
                        </div>
                        <h3 className="mt-2 font-display text-[20px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                          {m.title}
                        </h3>
                        {m.lessons.length > 0 && (
                          <ul className="mt-4 space-y-2">
                            {m.lessons.map((l) => (
                              <li
                                key={l.id}
                                className="flex items-center justify-between gap-4 text-[14px]"
                              >
                                <span className="text-[var(--color-ink)]">{l.title}</span>
                                <span className="whitespace-nowrap text-[var(--color-slate)]">
                                  {l.type} · {l.durationMin} min
                                </span>
                              </li>
                            ))}
                          </ul>
                        )}
                      </li>
                    ))}
                  </ol>
                )}
              </div>

              {course.outcomes && course.outcomes.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    What you'll learn
                  </h2>
                  <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-slate)]">
                    {course.outcomes.map((o) => (
                      <li key={o} className="flex gap-3">
                        <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
                        {o}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {course.prerequisites && course.prerequisites.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    Prerequisites
                  </h2>
                  <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-slate)]">
                    {course.prerequisites.map((p) => (
                      <li key={p} className="flex gap-3">
                        <span className="mt-2 inline-block h-1.5 w-1.5 flex-none rounded-full bg-[var(--color-blue)]" />
                        {p}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {detail?.testimonials && detail.testimonials.length > 0 && (
                <div>
                  <h2 className="font-display text-[26px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    What participants say
                  </h2>
                  <div className="mt-6 grid gap-4 sm:grid-cols-2">
                    {detail.testimonials.map((t, i) => (
                      <figure
                        key={i}
                        className="flex flex-col gap-4 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/30 p-6"
                      >
                        <blockquote className="text-[15px] leading-relaxed text-[var(--color-ink)]">
                          {t.quote}
                        </blockquote>
                        {t.author && (
                          <figcaption className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                            {t.author}
                          </figcaption>
                        )}
                      </figure>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <aside className="space-y-8">
              {(detail?.convenor || course.instructorName) && (
                <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-6">
                  <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                    Course convenor
                  </div>
                  <div className="mt-3 font-display text-[20px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
                    {detail?.convenor?.name || course.instructorName}
                  </div>
                  {(detail?.convenor?.role || course.instructorTitle) && (
                    <div className="mt-1 text-[14px] text-[var(--color-slate)]">
                      {detail?.convenor?.role || course.instructorTitle}
                    </div>
                  )}
                  {(detail?.convenor?.bio || course.instructorBio) && (
                    <p className="mt-4 whitespace-pre-wrap text-[14px] leading-relaxed text-[var(--color-slate)]">
                      {detail?.convenor?.bio || course.instructorBio}
                    </p>
                  )}
                  {detail?.convenor?.badges && detail.convenor.badges.length > 0 && (
                    <div className="mt-4 flex flex-wrap gap-1.5">
                      {detail.convenor.badges.map((badge) => (
                        <span
                          key={badge}
                          className="inline-flex items-center rounded-full bg-white px-2.5 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)] ring-1 ring-[var(--color-line)]"
                        >
                          {badge}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </aside>
          </div>
        </Container>
      </section>
    </>
  );
}
