import Link from "next/link";
import Image from "next/image";
import { notFound, redirect } from "next/navigation";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { requireUser } from "@/lib/auth/admin-guard";
import { getCourseForPlayer } from "@/lib/academy/queries";

export const dynamic = "force-dynamic";

export default async function CoursePlayerHome({
  params,
}: {
  params: Promise<{ courseId: string }>;
}) {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id!;
  const { courseId } = await params;

  const data = await getCourseForPlayer(courseId, userId);
  if (!data) {
    // Not enrolled or not published — send to catalog.
    redirect("/products/academy/courses");
  }

  const { course, modules, lessons, completedLessonIds } = data;
  const total = lessons.length;
  const done = lessons.filter((l) => completedLessonIds.has(l.id)).length;
  const pct = total > 0 ? Math.round((done / total) * 100) : 0;

  const firstIncomplete =
    lessons.find((l) => !completedLessonIds.has(l.id)) ?? lessons[0];

  if (!firstIncomplete && total === 0) {
    notFound();
  }

  return (
    <>
      <section className="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">
            <Link
              href="/account"
              className="inline-flex items-center gap-2 text-[13px] font-semibold text-[var(--color-slate)] transition-colors hover:text-[var(--color-blue)]"
            >
              <span>&larr;</span> Your account
            </Link>
            <div className="mt-8 grid gap-8 md:grid-cols-[1.3fr_1fr] md:items-start">
              <div>
                <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                  {course.level} · {course.topic}
                </div>
                <h1 className="mt-3 font-display text-[36px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)] md:text-[48px]">
                  {course.title}
                </h1>
                <div className="mt-6 max-w-md">
                  <div className="flex items-center justify-between text-[13px] text-[var(--color-slate)]">
                    <span>
                      {done} / {total} lessons complete
                    </span>
                    <span>{pct}%</span>
                  </div>
                  <div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-[var(--color-mist)]">
                    <div
                      className="h-full bg-[var(--color-blue)] transition-[width]"
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>
                <div className="mt-8 flex flex-wrap gap-4">
                  {firstIncomplete && (
                    <Button
                      href={`/account/academy/${course.id}/${firstIncomplete.id}`}
                    >
                      {done === 0 ? "Start first lesson" : "Resume"}
                    </Button>
                  )}
                  <Button href={`/products/academy/courses/${course.slug}`} variant="ghost">
                    Course overview
                  </Button>
                </div>
              </div>
              {course.coverPhoto && (
                <div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]">
                  <Image
                    src={course.coverPhoto}
                    alt={course.coverPhotoAlt ?? course.title}
                    fill
                    sizes="(min-width: 1024px) 400px, 100vw"
                    className="object-cover"
                  />
                </div>
              )}
            </div>
          </div>
        </Container>
      </section>

      <section className="bg-white py-16">
        <Container>
          <div className="mx-auto max-w-3xl">
            <h2 className="font-display text-[24px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
              Curriculum
            </h2>
            <ol className="mt-6 space-y-6">
              {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>
                  <ul className="mt-4 divide-y divide-[var(--color-line)]">
                    {m.lessons.map((l) => {
                      const isDone = completedLessonIds.has(l.id);
                      return (
                        <li
                          key={l.id}
                          className="flex items-center justify-between gap-4 py-3 text-[14px]"
                        >
                          <Link
                            href={`/account/academy/${course.id}/${l.id}`}
                            className="flex items-center gap-3 text-[var(--color-ink)] hover:text-[var(--color-blue)]"
                          >
                            <span
                              className={
                                isDone
                                  ? "inline-flex h-5 w-5 items-center justify-center rounded-full bg-[var(--color-blue)] text-[10px] font-bold text-white"
                                  : "inline-flex h-5 w-5 items-center justify-center rounded-full border border-[var(--color-line)] text-[10px] text-[var(--color-slate)]"
                              }
                              aria-hidden
                            >
                              {isDone ? "✓" : ""}
                            </span>
                            <span>{l.title}</span>
                          </Link>
                          <span className="whitespace-nowrap text-[var(--color-slate)]">
                            {l.type} · {l.durationMin} min
                          </span>
                        </li>
                      );
                    })}
                  </ul>
                </li>
              ))}
            </ol>
          </div>
        </Container>
      </section>
    </>
  );
}
