import type { Metadata } from "next";
import Link from "next/link";
import { ShoppingBag, ArrowRight } from "lucide-react";
import { requireUser } from "@/lib/auth/admin-guard";
import { listOrdersForUser } from "@/lib/store/queries";
import { formatMinor } from "@/lib/store/cart";
import { Button } from "@/components/Button";

export const metadata: Metadata = {
  title: "My orders",
  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): string {
  return d.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default async function MyOrdersPage() {
  const session = await requireUser();
  const userId = (session.user as { id?: string }).id;
  if (!userId) return null;
  const orders = await listOrdersForUser(userId);

  return (
    <>
      <div className="mb-6 flex items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[var(--color-mist)] text-[var(--color-blue)]">
          <ShoppingBag className="h-5 w-5" aria-hidden />
        </span>
        <div className="min-w-0 flex-1">
          <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
            Store
          </div>
          <h1 className="mt-1 font-display text-[28px] md:text-[34px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
            My orders
          </h1>
          <p className="mt-2 max-w-2xl text-[14px] leading-relaxed text-[var(--color-slate)]">
            Every order you&rsquo;ve placed, with its current status, invoice,
            and tracking info.
          </p>
        </div>
      </div>

      {orders.length === 0 ? (
        <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
          <ShoppingBag
            className="mx-auto h-8 w-8 text-[var(--color-slate)]"
            aria-hidden
          />
          <h2 className="mt-4 font-display text-[20px] font-extrabold text-[var(--color-ink)]">
            No orders yet
          </h2>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            Browse the store to find books, instruments, and OrthoGlobe merch.
          </p>
          <div className="mt-5">
            <Button href="/products/store" variant="primary">
              Browse the store
            </Button>
          </div>
        </div>
      ) : (
        <ul className="space-y-3">
          {orders.map((o) => {
            const s = STATUS_LABELS[o.status] ?? STATUS_LABELS.pending_invoice;
            return (
              <li key={o.id}>
                <Link
                  href={`/products/store/orders/${o.id}`}
                  className="group flex flex-wrap items-center gap-3 rounded-xl border border-[var(--color-line)] bg-white p-4 transition-[border-color] hover:border-[var(--color-blue)]"
                >
                  <div className="min-w-0 flex-1">
                    <div className="font-display text-[15px] font-extrabold text-[var(--color-ink)] group-hover:text-[var(--color-blue)]">
                      {o.orderNumber}
                    </div>
                    <div className="mt-0.5 text-[12px] text-[var(--color-slate)]">
                      Placed {formatDate(o.createdAt)} ·{" "}
                      {formatMinor(o.totalMinor, o.currency)}
                    </div>
                  </div>
                  <span
                    className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider ring-1 ring-inset ${s.tone}`}
                  >
                    {s.label}
                  </span>
                  <ArrowRight
                    className="h-4 w-4 text-[var(--color-slate)] transition-transform group-hover:translate-x-0.5 group-hover:text-[var(--color-blue)]"
                    aria-hidden
                  />
                </Link>
              </li>
            );
          })}
        </ul>
      )}
    </>
  );
}
