import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowRight, ShoppingBag } from "lucide-react";
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, settingNumber } from "@/lib/settings";
import { formatPrice } from "@/lib/money";
import { buildMetadata } from "@/lib/seo";
import { Button } from "@/components/ui/button";
import { CartLineItem } from "@/components/store/cart-line-item";
import { CouponForm } from "@/components/store/coupon-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.cart.title} — DAR ZELLIGE`,
    description: dict.cart.title,
    path: "/cart",
    noIndex: true,
  });
}

export default async function CartPage({ 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] = await Promise.all([getSessionUser(), getSettings()]);
  const address = user
    ? await prisma.customerAddress.findFirst({ where: { userId: user.id, isDefault: true } })
    : null;
  const country = address?.country ?? "MA";

  const cart = await getCartView(locale);
  const summary = await getCartSummary(cart, locale, country, settings);
  const freeThreshold = settingNumber(settings, "shipping.freeThreshold", 150000);
  const remaining = Math.max(0, freeThreshold - summary.subtotal);

  if (!cart || cart.items.length === 0) {
    return (
      <section className="shell flex min-h-[62vh] flex-col items-center justify-center py-20 text-center">
        <span className="flex h-16 w-16 items-center justify-center rounded-full border border-border">
          <ShoppingBag className="h-5 w-5 text-charcoal/40" strokeWidth={1.2} />
        </span>
        <h1 className="mt-6 font-serif text-4xl font-light tracking-tight">{dict.cart.empty}</h1>
        <p className="mt-3 max-w-sm text-[15px] leading-relaxed text-charcoal/50">{dict.cart.emptyDesc}</p>
        <Button asChild className="mt-8">
          <Link href={`/${locale}/shop`}>
            {dict.cart.emptyLink}
            <ArrowRight className="h-4 w-4 rtl:rotate-180" />
          </Link>
        </Button>
      </section>
    );
  }

  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.nav.cart}</p>
              <h1 className="mt-3 font-serif text-4xl font-light tracking-tight md:text-5xl">
                {dict.cart.title}
              </h1>
            </div>
            <ol className="flex items-center gap-3 text-[12px] uppercase tracking-[0.14em] text-charcoal/35">
              <li className="text-charcoal">01 {dict.nav.cart}</li>
              <li className="h-px w-6 bg-border" />
              <li>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 grid gap-12 py-10 md:py-14 lg:grid-cols-[1fr_360px] lg:gap-16">
        <div>
          <div className="flex items-center justify-between border-b border-border pb-4 text-[12px] uppercase tracking-[0.14em] text-charcoal/35">
            <span>{dict.cart.product}</span>
            <span>{dict.cart.quantity}</span>
          </div>

          {cart.items.map((item) => (
            <CartLineItem
              key={item.id}
              item={item}
              locale={locale}
              labels={{
                remove: dict.cart.remove,
                unavailable: dict.cart.stockWarning,
                quantity: dict.cart.quantity,
              }}
            />
          ))}

          {!cart.allAvailable && (
            <p className="mt-5 border border-terracotta/20 bg-terracotta/5 px-4 py-3 text-[13px] text-terracotta">
              {dict.cart.stockWarning}
            </p>
          )}

          <div className="mt-8 flex flex-wrap items-center justify-between gap-4">
            <Button asChild variant="ghost" className="px-0">
              <Link href={`/${locale}/shop`}>{dict.cart.continueShopping}</Link>
            </Button>
            <p className="text-[12px] uppercase tracking-[0.12em] text-charcoal/35">
              {cart.items.reduce((sum, item) => sum + item.quantity, 0)} {dict.checkout.summaryItems}
            </p>
          </div>
        </div>

        <aside className="h-fit border border-border bg-cream/50 p-5 md:p-6 lg:sticky lg:top-32">
          <h2 className="font-serif text-2xl font-light">{dict.checkout.summary}</h2>

          {country === "MA" && summary.total > 0 && (
            <div className="mt-5">
              {summary.freeShipping ? (
                <p className="flex items-center gap-2 text-[12px] uppercase tracking-[0.1em] text-olive">
                  <span className="h-1.5 w-1.5 rounded-full bg-olive" />
                  {dict.cart.freeShipping}
                </p>
              ) : (
                <>
                  <div className="h-px w-full bg-border">
                    <div
                      className="h-px bg-gold transition-all"
                      style={{ width: `${Math.min(100, (summary.subtotal / freeThreshold) * 100)}%` }}
                    />
                  </div>
                  <p className="mt-2 text-[12px] leading-relaxed text-charcoal/45">
                    {dict.cart.freeShipping} — {formatPrice(remaining, locale)}
                  </p>
                </>
              )}
            </div>
          )}

          <dl className="mt-5 space-y-3 text-[14px]">
            <div className="flex justify-between gap-4">
              <dt className="text-charcoal/50">{dict.cart.subtotal}</dt>
              <dd className="text-charcoal">{formatPrice(summary.subtotal, locale)}</dd>
            </div>
            {summary.discount > 0 && (
              <div className="flex justify-between gap-4">
                <dt className="text-olive">{dict.cart.discount}</dt>
                <dd className="text-olive">−{formatPrice(summary.discount, locale)}</dd>
              </div>
            )}
            <div className="flex justify-between gap-4">
              <dt className="text-charcoal/50">{dict.cart.shipping}</dt>
              <dd className="text-charcoal">
                {summary.shipping === 0 ? dict.common.free : formatPrice(summary.shipping, locale)}
              </dd>
            </div>
            <div className="flex items-baseline justify-between gap-4 border-t border-border pt-3">
              <dt className="text-[12px] uppercase tracking-[0.12em] text-charcoal/60">
                {dict.cart.orderTotal}
              </dt>
              <dd className="font-serif text-xl text-charcoal">{formatPrice(summary.total, locale)}</dd>
            </div>
          </dl>
          <p className="mt-2 text-[12px] leading-relaxed text-charcoal/35">{dict.cart.taxNote}</p>

          <div className="mt-5 border-t border-border pt-4">
            <p className="mb-2 text-[12px] uppercase tracking-[0.12em] text-charcoal/45">
              {dict.cart.coupon}
            </p>
            <CouponForm
              locale={locale}
              appliedCode={summary.coupon?.ok ? cart.couponCode : null}
              invalidCode={summary.coupon && !summary.coupon.ok ? cart.couponCode : null}
              labels={{
                coupon: dict.cart.coupon,
                placeholder: dict.cart.couponPlaceholder,
                apply: dict.checkout.couponApply,
                applied: dict.cart.couponApplied,
                invalid: dict.cart.couponInvalid,
                removed: dict.cart.couponRemoved,
              }}
            />
          </div>

          {cart.allAvailable ? (
            <Button asChild size="lg" className="mt-5 w-full">
              <Link href={`/${locale}/checkout`}>
                {dict.cart.checkout}
                <ArrowRight className="h-4 w-4 rtl:rotate-180" />
              </Link>
            </Button>
          ) : (
            <>
              <p className="mt-5 border border-terracotta/25 bg-terracotta/5 px-4 py-3 text-[12px] leading-relaxed text-terracotta">
                {dict.cart.stockWarning}
              </p>
              <Button size="lg" className="mt-2 w-full" disabled>
                {dict.cart.checkout}
              </Button>
            </>
          )}
          <p className="mt-3 text-center text-[12px] text-charcoal/35">{dict.cart.shippingNote}</p>
        </aside>
      </div>
    </>
  );
}