import type { Metadata } from "next";
import Link from "next/link";
import { eq, inArray } from "drizzle-orm";
import { GraduationCap, ArrowRight, Plus } from "lucide-react";
import { requireUser } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import {
  enrollments,
  courses,
  courseModules,
  lessons,
  lessonProgress,
} from "@/lib/db/schema";
import { Button } from "@/components/Button";

export const metadata: Metadata = {
  title: "My Academy",
  robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";

export default async function MyAcademyPage() {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id;
  if (!userId) return null;

  const enrolls = await db
    .select({ courseId: enrollments.courseId, at: enrollments.enrolledAt })
    .from(enrollments)
    .where(eq(enrollments.userId, userId));
  const courseIds = enrolls.map((e) => e.courseId);

  let items: Array<{
    id: string;
    slug: string;
    title: string;
    level: string;
    topic: string;
    description: string;
    totalLessons: number;
    completed: number;
  }> = [];

  if (courseIds.length > 0) {
    const courseRows = await db
      .select()
      .from(courses)
      .where(inArray(courses.id, courseIds));
    const moduleRows = await db
      .select()
      .from(courseModules)
      .where(inArray(courseModules.courseId, courseIds));
    const moduleIds = moduleRows.map((m) => m.id);
    const lessonRows =
      moduleIds.length === 0
        ? []
        : await db
            .select()
            .from(lessons)
            .where(inArray(lessons.moduleId, moduleIds));
    const progressRows = await db
      .select()
      .from(lessonProgress)
      .where(eq(lessonProgress.userId, userId));
    const completedIds = new Set(progressRows.map((p) => p.lessonId));
    items = courseRows.map((c) => {
      const cMods = moduleRows
        .filter((m) => m.courseId === c.id)
        .map((m) => m.id);
      const cLessons = lessonRows.filter((l) => cMods.includes(l.moduleId));
      return {
        id: c.id,
        slug: c.slug,
        title: c.title,
        level: c.level,
        topic: c.topic,
        description: c.shortDescription,
        totalLessons: cLessons.length,
        completed: cLessons.filter((l) => completedIds.has(l.id)).length,
      };
    });
  }

  return (
    <>
      <div className="mb-6 flex items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[var(--color-mist)] text-[var(--color-blue)]">
          <GraduationCap className="h-5 w-5" aria-hidden />
        </span>
        <div className="min-w-0 flex-1">
          <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
            Learning
          </div>
          <h1 className="mt-1 font-display text-[28px] md:text-[34px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
            My Academy
          </h1>
          <p className="mt-2 max-w-2xl text-[14px] leading-relaxed text-[var(--color-slate)]">
            Every course you&rsquo;re enrolled in, with your current progress.
          </p>
        </div>
      </div>

      <div className="mb-6">
        <Button
          href="/products/academy"
          variant="primary"
          className="!px-4 !py-2 !text-[13px]"
        >
          <Plus className="h-3.5 w-3.5" aria-hidden />
          Browse all courses
        </Button>
      </div>

      {items.length === 0 ? (
        <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
          <GraduationCap
            className="mx-auto h-8 w-8 text-[var(--color-slate)]"
            aria-hidden
          />
          <h2 className="mt-4 font-display text-[20px] font-extrabold text-[var(--color-ink)]">
            Not enrolled in any courses yet
          </h2>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            Explore Academy courses — each has video lessons, resources, and
            progress tracking.
          </p>
          <div className="mt-5">
            <Button href="/products/academy" variant="primary">
              Browse courses
            </Button>
          </div>
        </div>
      ) : (
        <ul className="grid gap-4 md:grid-cols-2">
          {items.map((c) => {
            const pct =
              c.totalLessons > 0
                ? Math.round((c.completed / c.totalLessons) * 100)
                : 0;
            return (
              <li key={c.id}>
                <Link
                  href={`/account/academy/${c.id}`}
                  className="group flex flex-col rounded-2xl border border-[var(--color-line)] bg-white p-5 transition-[border-color,box-shadow] hover:border-[var(--color-blue)] hover:shadow-[0_12px_32px_rgba(30,64,255,0.08)]"
                >
                  <div className="flex items-center justify-between">
                    <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
                      {c.level} · {c.topic}
                    </div>
                    <ArrowRight
                      className="h-4 w-4 text-[var(--color-slate)] transition-transform group-hover:translate-x-0.5 group-hover:text-[var(--color-blue)]"
                      aria-hidden
                    />
                  </div>
                  <div className="mt-2 font-display text-[18px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                    {c.title}
                  </div>
                  {c.description && (
                    <p className="mt-2 line-clamp-2 text-[13px] leading-relaxed text-[var(--color-slate)]">
                      {c.description}
                    </p>
                  )}
                  <div className="mt-5 flex items-center justify-between text-[12px] text-[var(--color-slate)]">
                    <span>
                      <strong className="text-[var(--color-ink)]">
                        {c.completed}
                      </strong>{" "}
                      / {c.totalLessons} lessons
                    </span>
                    <span className="font-semibold text-[var(--color-ink)]">
                      {pct}%
                    </span>
                  </div>
                  <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-[var(--color-mist)]">
                    <div
                      className="h-full rounded-full bg-[var(--color-blue)] transition-all"
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </Link>
              </li>
            );
          })}
        </ul>
      )}
    </>
  );
}
