import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowLeft, Check, Truck } 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";
import { cn } from "@/lib/utils";

const FLOW = ["PENDING", "CONFIRMED", "PROCESSING", "SHIPPED", "DELIVERED"] as const;

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

export default async function AccountOrderDetailPage({
  params,
}: {
  params: Promise<{ locale: string; id: string }>;
}) {
  const { locale: raw, id } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  const user = await requireUser(locale, `/${locale}/account/orders`);

  const order = await prisma.order.findFirst({
    where: { id, userId: user.id },
    include: { items: true },
  });
  if (!order) notFound();

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

  const cancelled = order.status === "CANCELLED";
  const stepIndex = FLOW.indexOf(order.status as (typeof FLOW)[number]);
  const paymentLabel =
    order.paymentMethod === "BANK_TRANSFER"
      ? dict.payment.BANK_TRANSFER
      : order.paymentMethod === "ONLINE"
        ? dict.payment.ONLINE
        : dict.payment.COD;

  return (
    <div>
      <Link
        href={`/${locale}/account/orders`}
        className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.12em] text-walnut hover:text-charcoal"
      >
        <ArrowLeft className="h-3.5 w-3.5 rtl:rotate-180" />
        {dict.account.backToOrders}
      </Link>

      <div className="mt-5 flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4">
        <div>
          <p className="eyebrow">{dict.account.orderNumber}</p>
          <h2 className="mt-2 font-mono text-2xl tracking-[0.08em]">{order.reference}</h2>
          <p className="mt-1 text-[13px] text-walnut">
            {dateFormat.format(order.createdAt)} · {dict.account.sampleOrder}
          </p>
        </div>
        <Badge variant={cancelled ? "outline" : "gold"}>
          {dict.status[order.status as keyof typeof dict.status] ?? order.status}
        </Badge>
      </div>

      {cancelled ? (
        <p className="mt-6 border border-terracotta/30 bg-cream px-4 py-3 text-[14px] text-terracotta">
          {dict.status.CANCELLED}
        </p>
      ) : (
        <ol className="mt-8 grid grid-cols-5 gap-2">
          {FLOW.map((step, index) => {
            const done = stepIndex >= index;
            return (
              <li key={step} className="relative">
                <div className={cn("h-px w-full", done ? "bg-gold" : "bg-border")} />
                <span
                  className={cn(
                    "mt-2 flex h-5 w-5 items-center justify-center rounded-full border text-[12px]",
                    done ? "border-gold bg-gold text-ivory" : "border-line text-pebble",
                  )}
                >
                  {done ? <Check className="h-2.5 w-2.5" /> : index + 1}
                </span>
                <p
                  className={cn(
                    "mt-2 min-w-0 break-words text-[12px] uppercase leading-tight tracking-[0.01em] sm:text-[12px] sm:tracking-[0.04em]",
                    done ? "text-charcoal" : "text-pebble",
                  )}
                >
                  {dict.status[step]}
                </p>
              </li>
            );
          })}
        </ol>
      )}

      <div className="mt-8 grid gap-8 lg:grid-cols-[1fr_300px]">
        <div>
          <h3 className="border-b border-line pb-3 text-[13px] font-medium uppercase tracking-[0.12em] text-walnut">
            {dict.account.items}
          </h3>
          <ul className="divide-y divide-line">
            {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 border border-line 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.08em] text-walnut">{item.variantName}</p>
                  )}
                  <p className="mt-1 text-[13px] text-walnut">
                    {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-line pt-4 text-[14px]">
            <div className="flex justify-between gap-4">
              <dt className="text-walnut">{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-walnut">{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-line pt-2">
              <dt className="text-[12px] uppercase tracking-[0.1em] text-walnut">{dict.cart.orderTotal}</dt>
              <dd className="font-serif text-xl">{formatPrice(order.total, locale)}</dd>
            </div>
          </dl>
        </div>

        <aside className="space-y-5">
          <section className="border border-line bg-cream p-5 shadow-panel">
            <h3 className="text-[12px] font-medium uppercase tracking-[0.12em] text-walnut">
              {dict.account.shippingAddress}
            </h3>
            <address className="mt-3 space-y-1 text-[14px] not-italic leading-relaxed text-walnut">
              <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>
          </section>

          <section className="border border-line bg-cream p-5 shadow-panel">
            <h3 className="text-[12px] font-medium uppercase tracking-[0.12em] text-walnut">{dict.account.payment}</h3>
            <p className="mt-2 text-[14px] text-charcoal">{paymentLabel}</p>
            <p className="mt-1 text-[13px] text-walnut">
              {dict.payment[order.paymentStatus as keyof typeof dict.payment] ?? order.paymentStatus}
            </p>
          </section>

          {(order.trackingNumber || order.shippingCarrier) && (
            <section className="border border-line bg-cream p-5 shadow-panel">
              <h3 className="flex items-center gap-1.5 text-[12px] font-medium uppercase tracking-[0.12em] text-walnut">
                <Truck className="h-3 w-3" />
                {dict.account.tracking}
              </h3>
              <p className="mt-2 text-[14px] text-charcoal">{order.shippingCarrier}</p>
              <p className="mt-1 font-mono text-[13px] text-walnut">{order.trackingNumber}</p>
            </section>
          )}

          {order.notes && (
            <section className="border border-line bg-cream p-5 shadow-panel">
              <h3 className="text-[12px] font-medium uppercase tracking-[0.12em] text-walnut">{dict.account.notes}</h3>
              <p className="mt-2 text-[14px] leading-relaxed text-walnut">{order.notes}</p>
            </section>
          )}

          <Button asChild variant="outline" className="w-full">
            <Link href={`/${locale}/shop`}>{dict.cart.continueShopping}</Link>
          </Button>
        </aside>
      </div>
    </div>
  );
}
