import { notFound } from "next/navigation";
import Link from "next/link";
import TicketCard from "./ticket-card";
import BrandLogo from "@/components/brand-logo";
import { eq } from "drizzle-orm";
import { db } from "@db/client";
import { orders } from "@db/schema";
import { getOrderWithTickets, type OrderEventSummary, type OrderTicketSummary } from "@db/queries/orders";
import { getMerchOrderDetail } from "@db/queries/merch";
import { formatPrice } from "@/lib/format";

export default async function OrderSuccessPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  // Poll briefly: fulfillment (Paystack callback/webhook, PayPal capture, or
  // the M-Pesa Daraja callback) can land just after the customer is
  // redirected back here, so the very first read may still show "pending".
  let order: {
    status: string;
    buyer_email: string | null;
    buyer_phone: string | null;
    event: OrderEventSummary | null;
  } | null = null;
  let tickets: OrderTicketSummary[] = [];

  for (let attempt = 0; attempt < 5; attempt++) {
    const result = await getOrderWithTickets(id);
    if (!result) break;
    order = result;
    if (result.status === "paid") {
      tickets = result.tickets;
      break;
    }
    await new Promise((r) => setTimeout(r, 1000));
  }

  if (!order) notFound();

  // Merch added on the event page in the same payment.
  const [link] = await db.select({ merchOrderId: orders.merchOrderId }).from(orders).where(eq(orders.id, id)).limit(1);
  const merch = link?.merchOrderId ? await getMerchOrderDetail(link.merchOrderId).catch(() => null) : null;

  return (
    <div className="min-h-screen bg-bg text-ink">
      <header className="border-b border-line bg-bg">
        <div className="max-w-2xl mx-auto px-4 h-14 flex items-center">
          <Link href="/" aria-label="VibePass Tickets — home">
            <BrandLogo size="sm" />
          </Link>
        </div>
      </header>

      <main className="max-w-2xl mx-auto px-4 py-10">
        {order.status !== "paid" ? (
          <p className="text-muted">
            We&apos;re still confirming your payment. Refresh this page in a moment, or check your
            email for confirmation.
          </p>
        ) : (
          <>
            <h1 className="text-2xl font-bold text-white mb-2">You&apos;re in! 🎟</h1>
            <p className="text-muted mb-8">
              A confirmation has been sent to {order.buyer_email}. Show these QR codes at the
              door. See you there.
            </p>

            <div className="grid gap-4">
              {tickets.map((t, i) => (
                <TicketCard
                  key={t.id}
                  index={i + 1}
                  code={t.code}
                  signature={t.signature}
                  attendeeName={t.attendee_name}
                  attendeePhone={order?.buyer_phone ?? null}
                  ticketTypeName={t.ticket_type_name}
                  eventTitle={order?.event?.title ?? ""}
                  coverImageUrl={order?.event?.cover_image_url ?? null}
                  startsAt={order!.event!.starts_at}
                  endsAt={order?.event?.ends_at ?? null}
                  storefront={order?.event?.organizer_name ?? null}
                  location={
                    order?.event?.venue
                      ? [order.event.venue, order.event.city].filter(Boolean).join(", ")
                      : order?.event?.city ?? null
                  }
                />
              ))}
            </div>

            {merch && (
              <section className="mt-8 rounded-2xl border border-line bg-panel p-5">
                <h2 className="text-lg font-bold text-white">Your merch 🛍</h2>
                <ul className="mt-3 space-y-1 text-sm">
                  {merch.items.map((i) => (
                    <li key={i.id} className="flex justify-between gap-3">
                      <span>
                        {i.quantity}× {i.productName}
                        {i.variantLabel && i.variantLabel !== "Standard" ? ` (${i.variantLabel})` : ""}
                      </span>
                      <span className="text-muted">{formatPrice(i.unitCents * i.quantity, "kes")}</span>
                    </li>
                  ))}
                </ul>
                {merch.order.status === "paid" ? (
                  <>
                    <p className="mt-4 text-sm text-muted">
                      {merch.order.fulfillment === "pickup" ? "Collect it with this pickup code:" : "Your delivery reference:"}
                    </p>
                    <p className="mt-1 font-mono text-3xl font-black tracking-widest text-brand-green-h">
                      {merch.order.pickupCode}
                    </p>
                    {merch.order.fulfillment === "pickup" && merch.shop.pickupInstructions && (
                      <p className="mt-2 text-sm text-muted">{merch.shop.pickupInstructions}</p>
                    )}
                    <Link href={`/shop/orders/${merch.order.id}`} className="mt-3 inline-block text-sm text-brand-green-h hover:underline">
                      Track your merch order →
                    </Link>
                  </>
                ) : (
                  <p className="mt-3 text-sm text-muted">Confirming your merch order…</p>
                )}
              </section>
            )}
          </>
        )}
      </main>
    </div>
  );
}
