import { redirect } from "next/navigation";
import { hasPaidRegistration, isOnTrial, ownsCourse, trialEnd } from "@/lib/access";
import { getCurrentUser } from "@/lib/auth";
import { hasLiveAgent } from "@/lib/db";
import { courses } from "@/lib/courses";
import { PayBox } from "@/components/PayBox";
import { COURSE_PRICE_GHS, REGISTRATION_PRICE_GHS } from "@/lib/pricing";

export const metadata = { title: "Pay" };

export default async function PayPage({
  searchParams,
}: {
  searchParams: Promise<{ course?: string }>;
}) {
  const user = await getCurrentUser();
  if (!user) redirect("/login?next=/pay");
  const { course: focus } = await searchParams;
  const paid = hasPaidRegistration(user);
  const trial = isOnTrial(user);
  const ends = trialEnd(user);
  const list = focus ? courses.filter((c) => c.slug === focus).concat(courses.filter((c) => c.slug !== focus)) : courses;
  const ownedCourses = new Set(await Promise.all(list.map(async (c) => (await ownsCourse(user, c.slug)) ? c.slug : "")));

  return (
    <div className="mx-auto max-w-6xl px-4 py-14">
      {!paid ? (
        <>
          <h1 className="font-display text-4xl text-forest">Pay ₵{REGISTRATION_PRICE_GHS} to enter</h1>
          <p className="mt-3 max-w-2xl text-forest/75">
            Registration opens all six blueprints for 72 hours. Paystack will offer MTN MoMo, Telecel,
            AirtelTigo, and cards. After the three days, each course is ₵{COURSE_PRICE_GHS} to keep.
          </p>
          <div className="mt-10 max-w-md">
            <PayBox kind="registration" title="Registration · 3 days of all courses" locked={false} />
          </div>
        </>
      ) : (
        <>
          <h1 className="font-display text-4xl text-forest">
            {trial ? "Keep a course after day 3" : "Unlock a course"}
          </h1>
          <p className="mt-3 max-w-2xl text-forest/75">
            {trial
              ? `All courses are open until ${ends.toLocaleString()}. After that they lock unless you pay ₵${COURSE_PRICE_GHS} each.`
              : `Your 3-day window has ended. Unlock any blueprint for ₵${COURSE_PRICE_GHS} with Paystack.`}
          </p>
          <div className="mt-10 grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {list.map((c) => (
              <PayBox
                key={c.slug}
                kind="course"
                course={c.slug}
                title={c.title}
                locked={ownedCourses.has(c.slug)}
              />
            ))}
          </div>
          <div className="mt-10 max-w-md">
            <PayBox kind="agent" title="Live coach · 30 days" locked={hasLiveAgent(user)} />
          </div>
        </>
      )}
    </div>
  );
}
