import Link from "next/link";
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 { SignatureCustomCursor } from "@/components/events/signature/SignatureCustomCursor";
import { CheckoutWizard } from "@/components/events/signature/checkout-wizard/CheckoutWizard";

/**
 * Ticket-purchase wizard for a specific sale phase — reached by selecting a
 * phase (Early Bird/Presale/Regular Sale) under a ticket category on the
 * event detail page (`/events/[slug]/detail`). Requires login up front
 * (rather than only at the final checkout API call) because the wizard's
 * in-memory state (quantity, per-holder identity data) would otherwise be
 * lost on a redirect after several steps of filling in forms.
 */
export default async function TicketSelectPage({
  params,
}: {
  params: Promise<{ slug: string; ticketPhaseId: string }>;
}) {
  const { slug, ticketPhaseId } = await params;

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

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

  const ticketType = event.ticket_types?.find((tt) => tt.phases?.some((p) => String(p.id) === ticketPhaseId));
  const ticketPhase = ticketType?.phases?.find((p) => String(p.id) === ticketPhaseId);

  if (!ticketType || !ticketPhase) {
    notFound();
  }

  return (
    <div>
      <SignatureCustomCursor />
      <div className="px-6 pt-6">
        <Link href={`/events/${slug}/detail`} className="text-sm font-medium text-kolabora-primary">
          &larr; Back
        </Link>
      </div>
      <CheckoutWizard event={event} ticketType={ticketType} ticketPhase={ticketPhase} />
    </div>
  );
}
