import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowLeft, Mail, MapPin, Phone, User } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { AdminPageHeader } from "@/components/admin/page-header";
import { OrderStatusBadge, PaymentStatusBadge } from "@/components/admin/status-badge";
import { OrderAdminPanel } from "@/components/admin/order-admin-panel";

const steps = ["PENDING", "CONFIRMED", "PROCESSING", "SHIPPED", "DELIVERED"];
const stepLabels: Record<string, string> = {
  PENDING: "Reçue",
  CONFIRMED: "Confirmée",
  PROCESSING: "Préparation",
  SHIPPED: "Expédiée",
  DELIVERED: "Livrée",
};

const paymentLabels: Record<string, string> = {
  COD: "Paiement à la livraison",
  BANK_TRANSFER: "Virement bancaire",
  ONLINE: "Paiement en ligne",
};

const countryNames = new Intl.DisplayNames(["fr"], { type: "region" });

export default async function AdminOrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const order = await prisma.order.findUnique({
    where: { id },
    include: {
      items: true,
      user: { select: { id: true, name: true, email: true, phone: true, createdAt: true } },
    },
  });

  if (!order) notFound();

  const currentStep = steps.indexOf(order.status);
  const cancelled = order.status === "CANCELLED";

  return (
    <div className="space-y-5">
      <Link
        href="/admin/orders"
        className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.14em] text-pebble hover:text-charcoal"
      >
        <ArrowLeft className="h-3.5 w-3.5" />
        Toutes les commandes
      </Link>

      <AdminPageHeader
        eyebrow={`Commande du ${new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" }).format(order.createdAt)}`}
        title={order.reference}
        description={`${order.items.length} article(s) · ${formatPrice(order.total)} · ${paymentLabels[order.paymentMethod] ?? order.paymentMethod}`}
        actions={
          <div className="flex items-center gap-2">
            <OrderStatusBadge status={order.status} />
            <PaymentStatusBadge status={order.paymentStatus} />
          </div>
        }
      />

      <div className="border border-line bg-cream p-4">
        {cancelled ? (
          <p className="text-[14px] text-terracotta">Cette commande a été annulée. Les articles ont été remis en stock.</p>
        ) : (
          <div className="flex flex-wrap items-center gap-2">
            {steps.map((step, index) => {
              const reached = index <= currentStep;
              return (
                <div key={step} className="flex flex-1 items-center gap-2">
                  <div className="flex items-center gap-2">
                    <span
                      className={
                        reached
                          ? "flex h-5 w-5 items-center justify-center rounded-full bg-charcoal text-[12px] text-ivory"
                          : "flex h-5 w-5 items-center justify-center rounded-full border border-line text-[12px] text-pebble"
                      }
                    >
                      {index + 1}
                    </span>
                    <span className={reached ? "text-[13px] text-charcoal" : "text-[13px] text-pebble"}>
                      {stepLabels[step]}
                    </span>
                  </div>
                  {index < steps.length - 1 && <div className={`h-px flex-1 ${index < currentStep ? "bg-charcoal/40" : "bg-border"}`} />}
                </div>
              );
            })}
          </div>
        )}
      </div>

      <div className="grid gap-4 xl:grid-cols-[1fr_360px]">
        <div className="space-y-4">
          <section className="border border-line bg-cream">
            <div className="border-b border-line px-5 py-4">
              <h2 className="font-serif text-xl font-light">Articles</h2>
            </div>
            <div className="divide-y divide-border">
              {order.items.map((item) => (
                <div key={item.id} className="flex gap-4 px-5 py-4">
                  <div className="relative h-16 w-14 shrink-0 overflow-hidden bg-cream">
                    {item.image ? (
                      <Image src={item.image} alt={item.name} fill sizes="56px" className="object-cover" />
                    ) : null}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <div>
                        {item.productId ? (
                          <Link href={`/admin/products/${item.productId}`} className="text-[14px] text-charcoal hover:underline">
                            {item.name}
                          </Link>
                        ) : (
                          <p className="text-[14px] text-charcoal">{item.name}</p>
                        )}
                        {item.variantName && <p className="mt-0.5 text-[12px] text-pebble">{item.variantName}</p>}
                        <p className="mt-1 font-mono text-[12px] text-pebble">{item.sku}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-[14px] tabular-nums text-charcoal">{formatPrice(item.total)}</p>
                        <p className="mt-0.5 text-[12px] text-pebble">
                          {item.quantity} × {formatPrice(item.unitPrice)}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div className="space-y-2 border-t border-line px-5 py-4 text-[14px]">
              <div className="flex justify-between text-pebble">
                <span>Sous-total</span>
                <span className="tabular-nums">{formatPrice(order.subtotal)}</span>
              </div>
              {order.discount > 0 && (
                <div className="flex justify-between text-olive">
                  <span>Remise {order.couponCode ? `(${order.couponCode})` : ""}</span>
                  <span className="tabular-nums">−{formatPrice(order.discount)}</span>
                </div>
              )}
              <div className="flex justify-between text-pebble">
                <span>Livraison</span>
                <span className="tabular-nums">{order.shipping === 0 ? "Offerte" : formatPrice(order.shipping)}</span>
              </div>
              <div className="flex justify-between border-t border-line pt-2 text-[15px] text-charcoal">
                <span>Total</span>
                <span className="tabular-nums">{formatPrice(order.total)}</span>
              </div>
            </div>
          </section>

          {order.notes && (
            <section className="border border-line bg-cream p-5">
              <h2 className="font-serif text-xl font-light">Note du client</h2>
              <p className="mt-3 whitespace-pre-line text-[14px] leading-relaxed text-walnut">{order.notes}</p>
            </section>
          )}

          <section className="border border-line bg-cream p-5">
            <div className="flex items-center justify-between">
              <h2 className="font-serif text-xl font-light">Client</h2>
              {order.user && (
                <Link href={`/admin/customers/${order.user.id}`} className="text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
                  Fiche client
                </Link>
              )}
            </div>
            <div className="mt-4 grid gap-4 sm:grid-cols-2">
              <div className="space-y-2 text-[14px] text-walnut">
                <p className="flex items-center gap-2"><User className="h-3.5 w-3.5 text-pebble" />{order.customerName}</p>
                <p className="flex items-center gap-2"><Mail className="h-3.5 w-3.5 text-pebble" />{order.email}</p>
                <p className="flex items-center gap-2"><Phone className="h-3.5 w-3.5 text-pebble" />{order.phone}</p>
              </div>
              <div className="space-y-1.5 text-[14px] leading-relaxed text-walnut">
                <p className="flex items-center gap-2 text-[12px] uppercase tracking-[0.12em] text-pebble">
                  <MapPin className="h-3.5 w-3.5" /> Livraison
                </p>
                <p>{order.addressLine1}</p>
                {order.addressLine2 && <p>{order.addressLine2}</p>}
                <p>{order.postalCode ? `${order.postalCode} ` : ""}{order.city}</p>
                <p>{countryNames.of(order.country) ?? order.country}</p>
              </div>
            </div>
            {order.user && (
              <p className="mt-4 border-t border-line pt-3 text-[12px] text-pebble">
                Compte client depuis {new Intl.DateTimeFormat("fr-FR", { month: "long", year: "numeric" }).format(order.user.createdAt)}
              </p>
            )}
          </section>
        </div>

        <aside className="space-y-4">
          <section className="border border-line bg-cream p-4">
            <h2 className="font-serif text-lg font-light">Gestion</h2>
            <div className="mt-4">
              <OrderAdminPanel
                id={order.id}
                status={order.status}
                paymentStatus={order.paymentStatus}
                shippingCarrier={order.shippingCarrier ?? ""}
                trackingNumber={order.trackingNumber ?? ""}
                adminNote={order.adminNote ?? ""}
              />
            </div>
          </section>

          <section className="border border-line bg-cream p-4 text-[13px]">
            <h2 className="font-serif text-lg font-light">Détails</h2>
            <dl className="mt-3 space-y-2.5">
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Référence</dt>
                <dd className="font-mono text-[13px] text-charcoal">{order.reference}</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Canal</dt>
                <dd className="text-charcoal">Boutique en ligne</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Langue</dt>
                <dd className="uppercase text-charcoal">{order.locale}</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Devise</dt>
                <dd className="text-charcoal">{order.currency}</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Transporteur</dt>
                <dd className="text-charcoal">{order.shippingCarrier || "—"}</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-pebble">Suivi</dt>
                <dd className="font-mono text-[13px] text-charcoal">{order.trackingNumber || "—"}</dd>
              </div>
            </dl>
          </section>
        </aside>
      </div>
    </div>
  );
}
