import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { requireUser } from "@/lib/auth/admin-guard";
import { getCourseForPlayer } from "@/lib/academy/queries";
import { renderMarkdown } from "@/lib/markdown/render";
import { VideoEmbed } from "@/components/academy/VideoEmbed";
import { markLessonComplete } from "../actions";

export const dynamic = "force-dynamic";

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

  const data = await getCourseForPlayer(courseId, userId);
  if (!data) redirect("/products/academy/courses");

  const { course, lessons, completedLessonIds } = data;
  const idx = lessons.findIndex((l) => l.id === lessonId);
  if (idx === -1) notFound();

  const lesson = lessons[idx];
  const prev = idx > 0 ? lessons[idx - 1] : null;
  const next = idx < lessons.length - 1 ? lessons[idx + 1] : null;
  const isDone = completedLessonIds.has(lesson.id);
  const contentHtml = lesson.content ? renderMarkdown(lesson.content) : "";
  const hasVideo = Boolean(lesson.videoUrl) && lesson.videoProvider !== "none";

  return (
    <Container>
      <div className="mx-auto max-w-3xl py-10 md:py-16">
        <Breadcrumbs
          items={[
            { label: "Academy", href: "/products/academy" },
            { label: "My learning", href: "/account" },
            { label: course.title, href: `/account/academy/${course.id}` },
            { label: lesson.title },
          ]}
        />

        <div className="mt-6 flex items-center gap-3 text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
          <span>Lesson {idx + 1} of {lessons.length}</span>
          <span className="text-[var(--color-line)]">·</span>
          <span className="text-[var(--color-slate)]">
            {lesson.type} · {lesson.durationMin} min
          </span>
        </div>
        <h1 className="mt-4 font-display text-[34px] font-extrabold leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)] md:text-[44px]">
          {lesson.title}
        </h1>

        {hasVideo ? (
          <div className="mt-10">
            <VideoEmbed
              provider={lesson.videoProvider}
              url={lesson.videoUrl}
              poster={lesson.videoPoster}
              title={lesson.title}
            />
          </div>
        ) : null}

        <article className="prose prose-slate prose-lg mt-10 max-w-none text-[var(--color-ink)]">
          {contentHtml ? (
            <div
              className="lesson-content text-[17px] leading-[1.7] text-[var(--color-ink)]"
              dangerouslySetInnerHTML={{ __html: contentHtml }}
            />
          ) : !hasVideo ? (
            <p className="text-[var(--color-slate)]">
              This lesson has no written content yet.
            </p>
          ) : null}
        </article>

        {lesson.keyPoints && lesson.keyPoints.length > 0 && (
          <div className="mt-10 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)]">
              Key points
            </div>
            <ul className="mt-4 space-y-3 text-[15px] text-[var(--color-ink)]">
              {lesson.keyPoints.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>
        )}

        {lesson.transcript && (
          <details className="mt-8 rounded-2xl border border-[var(--color-line)] bg-white">
            <summary className="cursor-pointer px-6 py-4 text-[14px] font-semibold text-[var(--color-ink)]">
              Transcript
            </summary>
            <div className="border-t border-[var(--color-line)] px-6 py-4 text-[14px] leading-relaxed text-[var(--color-slate)] whitespace-pre-wrap">
              {lesson.transcript}
            </div>
          </details>
        )}

        <div className="mt-12 flex flex-wrap items-center justify-between gap-4 border-t border-[var(--color-line)] pt-8">
          <div>
            {prev ? (
              <Button href={`/account/academy/${course.id}/${prev.id}`} variant="ghost">
                ← Previous
              </Button>
            ) : (
              <span />
            )}
          </div>
          <form action={markLessonComplete} className="flex items-center gap-3">
            <input type="hidden" name="courseId" value={course.id} />
            <input type="hidden" name="lessonId" value={lesson.id} />
            {next && <input type="hidden" name="next" value={next.id} />}
            <Button type="submit">
              {isDone
                ? next
                  ? "Next lesson →"
                  : "Finish course"
                : next
                ? "Mark complete & next →"
                : "Mark complete & finish"}
            </Button>
          </form>
        </div>
      </div>
    </Container>
  );
}
