import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import {
  CheckCircle2,
  ExternalLink,
  FileText,
  MapPin,
  Package,
  Receipt,
} from "lucide-react";
import { Container } from "@/components/Container";
import { Breadcrumbs } from "@/components/Breadcrumbs";
import { requireUser } from "@/lib/auth/admin-guard";
import { getOrderForUser } from "@/lib/store/queries";
import { formatMinor } from "@/lib/store/cart";

export const metadata: Metadata = {
  title: "Order confirmation",
  robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";

const STATUS_LABELS: Record<string, { label: string; tone: string }> = {
  pending_invoice: {
    label: "Pending invoice",
    tone: "bg-amber-50 text-amber-800 ring-amber-200",
  },
  invoiced: {
    label: "Invoice sent",
    tone: "bg-blue-50 text-blue-800 ring-blue-200",
  },
  paid: {
    label: "Paid",
    tone: "bg-emerald-50 text-emerald-800 ring-emerald-200",
  },
  shipped: {
    label: "Shipped",
    tone: "bg-[var(--color-mist)] text-[var(--color-blue)] ring-[var(--color-line)]",
  },
  delivered: {
    label: "Delivered",
    tone: "bg-emerald-50 text-emerald-800 ring-emerald-200",
  },
  cancelled: {
    label: "Cancelled",
    tone: "bg-slate-100 text-slate-700 ring-slate-200",
  },
};

function formatDate(d: Date | null | undefined): string {
  if (!d) return "—";
  return d.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
}

export default async function OrderConfirmationPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id ?? null;
  const { id } = await params;
  const data = await getOrderForUser(id, userId);
  if (!data) notFound();
  const { order, lines } = data;
  const statusInfo =
    STATUS_LABELS[order.status] ?? STATUS_LABELS.pending_invoice;

  return (
    <section className="bg-white pt-10 pb-16 md:pt-14 md:pb-20">
      <Container>
        <div className="mx-auto max-w-5xl">
          <Breadcrumbs
            items={[
              { label: "Store", href: "/products/store" },
              { label: "My orders", href: "/account/orders" },
              { label: order.orderNumber },
            ]}
          />
          <div className="mt-6 inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-emerald-700">
            <CheckCircle2 className="h-3 w-3" aria-hidden />
            Order received
          </div>
          <h1 className="mt-4 font-display text-[34px] md:text-[44px] font-extrabold leading-[1.05] tracking-[-0.02em] text-[var(--color-ink)]">
            Order {order.orderNumber}
          </h1>
          <p className="mt-3 max-w-2xl text-[15px] leading-relaxed text-[var(--color-slate)]">
            Thanks, {order.customerName}. A receipt is on its way to{" "}
            <strong>{order.customerEmail}</strong>. Our team will issue an
            invoice with the final total within two working days.
          </p>

          <div className="mt-6 flex flex-wrap items-center gap-3">
            <span
              className={`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-bold uppercase tracking-wider ring-1 ring-inset ${statusInfo.tone}`}
            >
              {statusInfo.label}
            </span>
            <span className="text-[12px] font-semibold text-[var(--color-slate)]">
              Placed {formatDate(order.createdAt)}
            </span>
          </div>

          <div className="mt-10 grid gap-8 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
            <div className="space-y-6">
              <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                <h2 className="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                  <Package className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                  Items
                </h2>
                <ul className="mt-4 divide-y divide-[var(--color-line)]">
                  {lines.map((l) => (
                    <li
                      key={l.id}
                      className="flex items-start justify-between gap-3 py-3 text-[14px]"
                    >
                      <div className="min-w-0">
                        <div className="font-semibold text-[var(--color-ink)]">
                          {l.productSlug ? (
                            <Link
                              href={`/products/store/${l.productSlug}`}
                              className="hover:text-[var(--color-blue)] hover:underline"
                            >
                              {l.productTitle}
                            </Link>
                          ) : (
                            l.productTitle
                          )}
                        </div>
                        <div className="text-[12px] text-[var(--color-slate)]">
                          {l.quantity} ×{" "}
                          {formatMinor(l.unitPriceMinor, order.currency)}
                        </div>
                      </div>
                      <div className="font-semibold text-[var(--color-ink)]">
                        {formatMinor(l.lineTotalMinor, order.currency)}
                      </div>
                    </li>
                  ))}
                </ul>
                <dl className="mt-4 space-y-2 border-t border-[var(--color-line)] pt-4 text-[14px]">
                  <div className="flex justify-between">
                    <dt className="text-[var(--color-slate)]">Subtotal</dt>
                    <dd className="font-semibold text-[var(--color-ink)]">
                      {formatMinor(order.subtotalMinor, order.currency)}
                    </dd>
                  </div>
                  <div className="flex justify-between">
                    <dt className="text-[var(--color-slate)]">Shipping</dt>
                    <dd className="font-semibold text-[var(--color-ink)]">
                      {order.shippingMinor === 0
                        ? "Free"
                        : formatMinor(order.shippingMinor, order.currency)}
                    </dd>
                  </div>
                  <div className="flex justify-between border-t border-[var(--color-line)] pt-2">
                    <dt className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                      Total
                    </dt>
                    <dd className="font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                      {formatMinor(order.totalMinor, order.currency)}
                    </dd>
                  </div>
                </dl>
              </div>

              {(order.trackingUrl ||
                order.trackingNumber ||
                order.shippedAt) && (
                <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                  <h2 className="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                    <Package className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                    Tracking
                  </h2>
                  {order.shippedAt && (
                    <p className="mt-2 text-[13px] text-[var(--color-slate)]">
                      Shipped {formatDate(order.shippedAt)}
                    </p>
                  )}
                  {order.trackingNumber && (
                    <p className="mt-1 text-[13px]">
                      Reference:{" "}
                      <code className="rounded bg-[var(--color-mist)] px-1.5 py-0.5 font-mono text-[12px] text-[var(--color-blue)]">
                        {order.trackingNumber}
                      </code>
                    </p>
                  )}
                  {order.trackingUrl && (
                    <a
                      href={order.trackingUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="mt-3 inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
                    >
                      Track with courier
                      <ExternalLink className="h-3 w-3" aria-hidden />
                    </a>
                  )}
                </div>
              )}

              {order.invoiceUrl && (
                <div className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                  <h2 className="flex items-center gap-2 font-display text-[18px] font-extrabold text-[var(--color-ink)]">
                    <FileText className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                    Invoice
                  </h2>
                  <a
                    href={order.invoiceUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="mt-3 inline-flex items-center gap-1 rounded-lg border border-[var(--color-line)] bg-white px-3 py-1.5 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  >
                    Open invoice
                    <ExternalLink className="h-3 w-3" aria-hidden />
                  </a>
                </div>
              )}
            </div>

            <aside>
              <div className="space-y-4 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-6">
                <h2 className="flex items-center gap-2 font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                  <MapPin className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                  Shipping to
                </h2>
                <div className="rounded-lg border border-[var(--color-line)] bg-white p-3 text-[13px] leading-relaxed text-[var(--color-ink)]">
                  <div className="font-semibold">{order.customerName}</div>
                  <div className="mt-1 whitespace-pre-line">
                    {order.shippingAddress}
                  </div>
                  <div className="mt-1 font-semibold">
                    {order.shippingCountry}
                  </div>
                </div>
                <div className="text-[12px] text-[var(--color-slate)]">
                  Contact: {order.customerEmail}
                  {order.customerPhone && (
                    <>
                      <br />
                      Phone: {order.customerPhone}
                    </>
                  )}
                </div>
              </div>
              <div className="mt-4 rounded-2xl border border-[var(--color-line)] bg-white p-5">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  <Receipt className="mr-1 inline h-3 w-3 align-[-2px]" aria-hidden />
                  Need help?
                </div>
                <p className="mt-2 text-[13px] leading-relaxed text-[var(--color-slate)]">
                  Reply to the receipt email or message{" "}
                  <a
                    href="mailto:store@orthoglobe.org"
                    className="font-semibold text-[var(--color-blue)] hover:underline"
                  >
                    store@orthoglobe.org
                  </a>{" "}
                  with this order number.
                </p>
              </div>
              <div className="mt-4 text-center">
                <Link
                  href="/products/store"
                  className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
                >
                  Keep shopping →
                </Link>
              </div>
            </aside>
          </div>
        </div>
      </Container>
    </section>
  );
}
