import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { cookies } from "next/headers";
import { CheckCircle2, Mail, Package, Truck } from "lucide-react";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { prisma } from "@/lib/prisma";
import { getSessionUser } from "@/lib/auth-helpers";
import { formatPrice } from "@/lib/money";
import { buildMetadata } from "@/lib/seo";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

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.successTitle} — DAR ZELLIGE`,
    description: dict.checkout.successTitle,
    path: "/checkout",
    noIndex: true,
  });
}

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

  const order = await prisma.order.findUnique({
    where: { reference },
    include: { items: true },
  });
  if (!order) notFound();

  const [user, cookieStore] = await Promise.all([getSessionUser(), cookies()]);
  const lastReference = cookieStore.get("dz_last_order")?.value;
  const owns = user?.id && order.userId === user.id;
  if (!owns && lastReference !== reference) notFound();

  const date = new Intl.DateTimeFormat(locale === "ar" ? "ar-MA" : locale === "en" ? "en-GB" : "fr-FR", {
    day: "numeric",
    month: "long",
    year: "numeric",
  }).format(order.createdAt);

  const paymentLabel =
    order.paymentMethod === "BANK_TRANSFER"
      ? dict.payment.BANK_TRANSFER
      : order.paymentMethod === "ONLINE"
        ? dict.payment.ONLINE
        : dict.payment.COD;

  return (
    <>
      <section className="border-b border-border bg-cream/50">
        <div className="shell py-14 text-center md:py-20">
          <span className="mx-auto flex h-16 w-16 items-center justify-center rounded-full border border-olive/30 bg-olive/5">
            <CheckCircle2 className="h-7 w-7 text-olive" strokeWidth={1.2} />
          </span>
          <p className="eyebrow mt-6">{dict.checkout.orderRef}</p>
          <h1 className="mt-3 font-serif text-4xl font-light tracking-tight md:text-5xl">
            {dict.checkout.successTitle}
          </h1>
          <p className="mx-auto mt-4 max-w-lg text-[15px] leading-relaxed text-charcoal/55">
            {dict.checkout.successDesc}
          </p>
          <p className="mt-6 inline-block border border-charcoal/20 px-5 py-2 font-mono text-lg tracking-[0.12em] text-charcoal">
            {order.reference}
          </p>
          <p className="mt-2 text-[12px] uppercase tracking-[0.12em] text-charcoal/35">{date}</p>
        </div>
      </section>

      <div className="shell grid gap-10 py-12 md:py-16 lg:grid-cols-[1fr_380px] lg:gap-16">
        <div>
          <h2 className="border-b border-border pb-3 text-[12px] uppercase tracking-[0.16em]">
            {dict.account.orderDetails}
          </h2>
          <ul className="divide-y divide-border">
            {order.items.map((item) => (
              <li key={item.id} className="flex items-center gap-4 py-4">
                <div className="relative h-20 w-16 shrink-0 overflow-hidden bg-sand/20">
                  {item.image && (
                    <Image src={item.image} alt={item.name} fill sizes="64px" className="object-cover" />
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <p className="font-serif text-base text-charcoal">{item.name}</p>
                  {item.variantName && (
                    <p className="text-[12px] uppercase tracking-[0.1em] text-charcoal/35">
                      {item.variantName}
                    </p>
                  )}
                  <p className="mt-1 text-[12px] text-charcoal/40">
                    {item.quantity} × {formatPrice(item.unitPrice, locale)}
                  </p>
                </div>
                <p className="text-[14px] text-charcoal">{formatPrice(item.total, locale)}</p>
              </li>
            ))}
          </ul>

          <dl className="ml-auto mt-4 max-w-xs space-y-2 border-t border-border pt-4 text-[13px]">
            <div className="flex justify-between gap-4">
              <dt className="text-charcoal/50">{dict.cart.subtotal}</dt>
              <dd>{formatPrice(order.subtotal, locale)}</dd>
            </div>
            {order.discount > 0 && (
              <div className="flex justify-between gap-4 text-olive">
                <dt>{dict.cart.discount}</dt>
                <dd>−{formatPrice(order.discount, locale)}</dd>
              </div>
            )}
            <div className="flex justify-between gap-4">
              <dt className="text-charcoal/50">{dict.cart.shipping}</dt>
              <dd>{order.shipping === 0 ? dict.common.free : formatPrice(order.shipping, locale)}</dd>
            </div>
            <div className="flex items-baseline justify-between gap-4 border-t border-border pt-2">
              <dt className="text-[12px] uppercase tracking-[0.12em]">{dict.cart.orderTotal}</dt>
              <dd className="font-serif text-xl">{formatPrice(order.total, locale)}</dd>
            </div>
          </dl>

          <div className="mt-10 grid gap-6 border-t border-border pt-8 sm:grid-cols-3">
            {[
              { icon: Mail, title: dict.checkout.contact, text: order.email },
              { icon: Truck, title: dict.account.shippingAddress, text: `${order.addressLine1}, ${order.city}` },
              { icon: Package, title: dict.account.payment, text: paymentLabel },
            ].map((block) => (
              <div key={block.title}>
                <block.icon className="h-4 w-4 text-gold" strokeWidth={1.3} />
                <p className="mt-2 text-[12px] uppercase tracking-[0.14em] text-charcoal/35">
                  {block.title}
                </p>
                <p className="mt-1 break-words text-[13px] leading-relaxed text-charcoal/65">{block.text}</p>
              </div>
            ))}
          </div>
        </div>

        <aside className="h-fit border border-border bg-cream/50 p-6">
          <div className="flex items-center justify-between gap-3">
            <h2 className="font-serif text-xl font-light">{dict.account.shippingAddress}</h2>
            <Badge variant="outline">{dict.status[order.status as keyof typeof dict.status] ?? order.status}</Badge>
          </div>
          <address className="mt-4 space-y-1 text-[14px] not-italic leading-relaxed text-charcoal/60">
            <p className="text-charcoal">{order.customerName}</p>
            <p>{order.addressLine1}</p>
            {order.addressLine2 && <p>{order.addressLine2}</p>}
            <p>
              {order.postalCode ? `${order.postalCode} ` : ""}
              {order.city}
            </p>
            <p>{dict.countries[order.country as keyof typeof dict.countries] ?? order.country}</p>
            <p>{order.phone}</p>
          </address>

          <div className="mt-5 border-t border-border pt-4">
            <p className="text-[12px] uppercase tracking-[0.14em] text-charcoal/35">
              {dict.account.payment}
            </p>
            <p className="mt-1 text-[14px] text-charcoal">{paymentLabel}</p>
          </div>

          <p className="mt-5 border-t border-border pt-4 text-[12px] leading-relaxed text-charcoal/45">
            {dict.checkout.confirmationNote}
          </p>
          <p className="mt-3 border border-gold/25 bg-sand/15 px-3 py-2 text-[12px] leading-relaxed text-charcoal/55">
            {dict.checkout.demoNotice}
          </p>

          <div className="mt-6 space-y-2">
            <Button asChild className="w-full">
              <Link href={`/${locale}`}>{dict.checkout.backHome}</Link>
            </Button>
            {user ? (
              <Button asChild variant="outline" className="w-full">
                <Link href={`/${locale}/account/orders`}>{dict.checkout.viewOrders}</Link>
              </Button>
            ) : (
              <Button asChild variant="outline" className="w-full">
                <Link href={`/${locale}/shop`}>{dict.cart.emptyLink}</Link>
              </Button>
            )}
          </div>
        </aside>
      </div>
    </>
  );
}