import { notFound, redirect } from "next/navigation";
import { ApiError } from "@/lib/api/server";
import { getEventBySlug } from "@/lib/api/events";
import { getCurrentUser } from "@/lib/api/auth";
import { CheckoutForm } from "@/components/checkout/checkout-form";
import { formatDate } from "@/lib/format";

export default async function CheckoutPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;

  const user = await getCurrentUser();
  if (!user) {
    redirect(`/login?next=/checkout/${slug}`);
  }

  const event = await getEventBySlug(slug)
    .then((res) => res.data)
    .catch((error) => {
      if (error instanceof ApiError && error.status === 404) {
        notFound();
      }
      throw error;
    });

  const ticketTypes = (event.ticket_types ?? []).filter((tt) => tt.phases?.some((p) => p.status === "available"));

  return (
    <div className="mx-auto max-w-2xl px-6 py-10">
      <h1 className="text-2xl font-semibold">Checkout</h1>
      <p className="mt-1 text-sm text-kolabora-neutral-dark/70">
        {event.title} &middot; {formatDate(event.start_date)}
        {event.location ? ` · ${event.location}` : ""}
      </p>

      {ticketTypes.length === 0 ? (
        <p className="mt-8 text-kolabora-neutral-dark/70">
          No tickets are currently on sale for this event.
        </p>
      ) : (
        <CheckoutForm event={event} ticketTypes={ticketTypes} user={user} />
      )}
    </div>
  );
}
