import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowRight, Heart, MapPin, Package, Wallet } from "lucide-react";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { requireUser } from "@/lib/auth-helpers";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { buildMetadata } from "@/lib/seo";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

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

export default async function AccountPage({ 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 = await requireUser(locale, `/${locale}/account`);

  const [orders, spent, wishlistCount, recentOrders, defaultAddress] = await Promise.all([
    prisma.order.count({ where: { userId: user.id } }),
    prisma.order.aggregate({
      where: { userId: user.id, status: { not: "CANCELLED" } },
      _sum: { total: true },
    }),
    prisma.wishlistItem.count({ where: { wishlist: { userId: user.id } } }),
    prisma.order.findMany({
      where: { userId: user.id },
      orderBy: { createdAt: "desc" },
      take: 3,
      include: { items: true },
    }),
    prisma.customerAddress.findFirst({ where: { userId: user.id, isDefault: true } }),
  ]);

  const stats = [
    { icon: Package, label: dict.account.totalOrders, value: String(orders) },
    { icon: Wallet, label: dict.account.totalSpent, value: formatPrice(spent._sum.total ?? 0, locale) },
    { icon: Heart, label: dict.account.wishlistCount, value: String(wishlistCount) },
  ];

  return (
    <div className="space-y-10">
      <div className="grid gap-px overflow-hidden border border-line bg-line shadow-panel sm:grid-cols-3">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-cream p-5">
            <stat.icon className="h-4 w-4 text-gold-ink" strokeWidth={1.3} />
            <p className="mt-3 font-serif text-3xl font-light text-charcoal">{stat.value}</p>
            <p className="mt-1.5 text-[13px] font-medium uppercase tracking-[0.1em] text-walnut">{stat.label}</p>
          </div>
        ))}
      </div>

      <section className="border border-line bg-cream p-5 shadow-panel">
        <div className="flex items-center justify-between gap-4 border-b border-line pb-3">
          <h2 className="text-[14px] font-medium uppercase tracking-[0.12em] text-walnut">{dict.account.recentOrders}</h2>
          <Link
            href={`/${locale}/account/orders`}
            className="flex items-center gap-1.5 text-[12px] uppercase tracking-[0.1em] text-walnut hover:text-charcoal"
          >
            {dict.common.viewAll}
            <ArrowRight className="h-3 w-3 rtl:rotate-180" />
          </Link>
        </div>

        {recentOrders.length === 0 ? (
          <div className="py-10 text-center">
            <p className="font-serif text-xl text-charcoal">{dict.account.noOrders}</p>
            <p className="mt-1 text-[13px] text-pebble">{dict.account.noOrdersDesc}</p>
            <Button asChild variant="outline" className="mt-5">
              <Link href={`/${locale}/shop`}>{dict.cart.emptyLink}</Link>
            </Button>
          </div>
        ) : (
          <ul className="divide-y divide-line">
            {recentOrders.map((order) => (
              <li key={order.id}>
                <Link
                  href={`/${locale}/account/orders/${order.id}`}
                  className="flex flex-wrap items-center justify-between gap-3 px-1 py-4 transition-colors hover:bg-parchment/60"
                >
                  <div>
                    <p className="font-mono text-[13px] tracking-[0.08em] text-charcoal">{order.reference}</p>
                    <p className="mt-1 text-[13px] text-pebble">
                      {new Intl.DateTimeFormat(locale === "ar" ? "ar-MA" : locale === "en" ? "en-GB" : "fr-FR", {
                        day: "numeric",
                        month: "long",
                        year: "numeric",
                      }).format(order.createdAt)}{" "}
                      · {order.items.length} {dict.account.items}
                    </p>
                  </div>
                  <div className="flex items-center gap-4">
                    <Badge variant={order.status === "CANCELLED" ? "outline" : "gold"}>
                      {dict.status[order.status as keyof typeof dict.status] ?? order.status}
                    </Badge>
                    <p className="text-[14px] text-charcoal">{formatPrice(order.total, locale)}</p>
                  </div>
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>

      <div className="grid gap-6 md:grid-cols-2">
        <section className="border border-line bg-cream p-5 shadow-panel">
          <div className="flex items-center gap-2 border-b border-line pb-3">
            <MapPin className="h-3.5 w-3.5 text-gold-ink" strokeWidth={1.4} />
            <h2 className="text-[14px] font-medium uppercase tracking-[0.12em] text-walnut">{dict.account.shippingAddress}</h2>
          </div>
          {defaultAddress ? (
            <div className="mt-4 text-[14px] leading-relaxed text-walnut">
              <p className="text-charcoal">{defaultAddress.fullName}</p>
              <p className="mt-1">{defaultAddress.addressLine1}</p>
              {defaultAddress.addressLine2 && <p>{defaultAddress.addressLine2}</p>}
              <p>
                {defaultAddress.postalCode ? `${defaultAddress.postalCode} ` : ""}
                {defaultAddress.city}
              </p>
              <p>{dict.countries[defaultAddress.country as keyof typeof dict.countries] ?? defaultAddress.country}</p>
              <Link
                href={`/${locale}/account/addresses`}
                className="mt-3 inline-block text-[12px] uppercase tracking-[0.1em] text-charcoal underline underline-offset-4"
              >
                {dict.account.editAddress}
              </Link>
            </div>
          ) : (
            <div className="mt-4">
              <p className="text-[13px] text-pebble">{dict.account.noAddresses}</p>
              <Link
                href={`/${locale}/account/addresses`}
                className="mt-3 inline-block text-[12px] uppercase tracking-[0.1em] text-charcoal underline underline-offset-4"
              >
                {dict.account.addAddress}
              </Link>
            </div>
          )}
        </section>

        <section className="border border-line bg-cream p-5 shadow-panel">
          <div className="flex items-center gap-2 border-b border-line pb-3">
            <Heart className="h-3.5 w-3.5 text-gold-ink" strokeWidth={1.4} />
            <h2 className="text-[14px] font-medium uppercase tracking-[0.12em] text-walnut">{dict.wishlist.title}</h2>
          </div>
          <p className="mt-4 font-serif text-2xl font-light">
            {wishlistCount} {dict.account.wishlistCount.toLowerCase()}
          </p>
          <p className="mt-1 text-[14px] leading-relaxed text-walnut">
            {wishlistCount > 0 ? dict.wishlist.emptyDesc : dict.wishlist.empty}
          </p>
          <Link
            href={`/${locale}/account/wishlist`}
            className="mt-3 inline-block text-[12px] uppercase tracking-[0.1em] text-charcoal underline underline-offset-4"
          >
            {dict.common.viewAll}
          </Link>
        </section>
      </div>
    </div>
  );
}
