import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { getCartSummary, getCartView } from "@/lib/cart";
import { getSessionUser } from "@/lib/auth-helpers";
import { prisma } from "@/lib/prisma";
import { getSettings } from "@/lib/settings";
import { shippingConfig } from "@/lib/shipping";
import { buildMetadata } from "@/lib/seo";
import { CheckoutForm } from "@/components/store/checkout-form";

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) return {};
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  return buildMetadata({
    locale,
    title: `${dict.checkout.title} — DAR ZELLIGE`,
    description: dict.checkout.title,
    path: "/checkout",
    noIndex: true,
  });
}

export default async function CheckoutPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);

  const [user, settings, cart] = await Promise.all([
    getSessionUser(),
    getSettings(),
    getCartView(locale),
  ]);

  if (!cart || cart.items.length === 0) redirect(`/${locale}/cart`);

  const address = user
    ? await prisma.customerAddress.findFirst({ where: { userId: user.id, isDefault: true } })
    : null;
  const country = address?.country ?? "MA";
  const summary = await getCartSummary(cart, locale, country, settings);
  const config = shippingConfig(settings);

  return (
    <>
      <section className="border-b border-border bg-cream/40">
        <div className="shell py-10 md:py-14">
          <div className="flex flex-col justify-between gap-4 md:flex-row md:items-end">
            <div>
              <p className="eyebrow">{dict.checkout.title}</p>
              <h1 className="mt-3 font-serif text-4xl font-light tracking-tight md:text-5xl">
                {dict.checkout.title}
              </h1>
            </div>
            <ol className="flex items-center gap-3 text-[12px] uppercase tracking-[0.14em] text-charcoal/35">
              <li>
                <Link href={`/${locale}/cart`} className="hover:text-charcoal">
                  01 {dict.nav.cart}
                </Link>
              </li>
              <li className="h-px w-6 bg-border" />
              <li className="text-charcoal">02 {dict.checkout.delivery}</li>
              <li className="h-px w-6 bg-border" />
              <li>03 {dict.checkout.successTitle.split(" ")[0]}</li>
            </ol>
          </div>
        </div>
      </section>

      <div className="shell py-10 md:py-14">
        <CheckoutForm
          locale={locale}
          isAuthenticated={Boolean(user)}
          defaults={{
            fullName: user?.name ?? "",
            email: user?.email ?? "",
            phone: user?.phone ?? "",
            country,
            city: address?.city ?? "",
            addressLine1: address?.addressLine1 ?? "",
            addressLine2: address?.addressLine2 ?? "",
            postalCode: address?.postalCode ?? "",
          }}
          summary={{
            subtotal: summary.subtotal,
            discount: summary.discount,
            shipping: summary.shipping,
            total: summary.total,
          }}
          items={cart.items.map((item) => ({
            id: item.id,
            name: item.name,
            variantName: item.variantName,
            image: item.image,
            quantity: item.quantity,
            lineTotal: item.lineTotal,
          }))}
          config={config}
          labels={{
            contact: dict.checkout.contact,
            delivery: dict.checkout.delivery,
            payment: dict.checkout.payment,
            fullName: dict.checkout.fullName,
            email: dict.checkout.email,
            phone: dict.checkout.phone,
            country: dict.checkout.country,
            city: dict.checkout.city,
            address: dict.checkout.address,
            address2: dict.checkout.address2,
            postalCode: dict.checkout.postalCode,
            notes: dict.checkout.notes,
            notesPlaceholder: dict.checkout.notesPlaceholder,
            cod: dict.checkout.paymentCod,
            codDesc: dict.checkout.paymentCodDesc,
            bank: dict.checkout.paymentBank,
            bankDesc: dict.checkout.paymentBankDesc,
            online: dict.checkout.paymentOnline,
            onlineDesc: dict.checkout.paymentOnlineDesc,
            placeOrder: dict.checkout.placeOrder,
            processing: dict.checkout.processing,
            terms: dict.checkout.terms,
            summary: dict.checkout.summary,
            items: dict.checkout.summaryItems,
            subtotal: dict.cart.subtotal,
            shipping: dict.cart.shipping,
            discount: dict.cart.discount,
            total: dict.cart.orderTotal,
            free: dict.common.free,
            secure: dict.checkout.secure,
            demoNotice: dict.checkout.demoNotice,
            loginPrompt: dict.checkout.loginPrompt,
            loginLink: dict.checkout.loginLink,
            required: dict.checkout.requiredFields,
          }}
        />
      </div>
    </>
  );
}