import Link from "next/link";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { prisma } from "@/lib/prisma";
import { whatsappLink, DEFAULT_CHECKOUT_PAUSED_MESSAGE } from "@/lib/site";
import CheckoutForm from "@/components/CheckoutForm";

export default async function CheckoutPage() {
  const storeSettings = await prisma.storeSettings.findFirst();
  if (!(storeSettings?.salesEnabled ?? true)) {
    const pausedMessage = storeSettings?.checkoutPausedMessage?.trim() || DEFAULT_CHECKOUT_PAUSED_MESSAGE;
    return (
      <div className="mx-auto max-w-md px-4 py-16 text-center sm:px-6">
        <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Checkout is temporarily paused</h1>
        <p className="mt-3 text-sm text-stone-600">{pausedMessage}</p>
        <a
          href={whatsappLink("Hi! I'd like to place an order.")}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-6 inline-block rounded-md bg-emerald-500 px-6 py-3 text-sm font-semibold text-white hover:bg-emerald-600"
        >
          WhatsApp us
        </a>
        <div className="mt-4">
          <Link href="/shop" className="text-sm font-medium text-rose-700 hover:underline">
            ← Continue browsing
          </Link>
        </div>
      </div>
    );
  }

  const customerId = await getCurrentCustomerId();
  if (!customerId) return <CheckoutForm savedAddresses={[]} customerEmail={null} />;

  const [customer, addresses] = await Promise.all([
    prisma.customer.findUnique({ where: { id: customerId } }),
    prisma.customerAddress.findMany({ where: { customerId }, orderBy: [{ isDefault: "desc" }, { createdAt: "asc" }] }),
  ]);

  return <CheckoutForm savedAddresses={addresses} customerEmail={customer?.email ?? null} />;
}
