import type { Metadata } from "next";
import Link from "next/link";
import { ShoppingBag } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import {
  listOrdersForAdmin,
  countPendingOrders,
} from "@/lib/store/queries";
import { formatMinor } from "@/lib/store/cart";
import {
  AdminHeading,
  DataTable,
  EmptyState,
  FilterPill,
  KpiCard,
  StatusBadge,
  Toolbar,
  formatAdminDateTime,
  type Column,
} from "@/components/admin";

export const metadata: Metadata = { title: "Store orders" };
export const dynamic = "force-dynamic";

const STATUS_FILTERS = [
  "all",
  "pending_invoice",
  "invoiced",
  "paid",
  "shipped",
  "delivered",
  "cancelled",
] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];

const STATUS_PRETTY: Record<string, string> = {
  pending_invoice: "pending",
  invoiced: "invoiced",
  paid: "paid",
  shipped: "shipped",
  delivered: "delivered",
  cancelled: "cancelled",
};

function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}

export default async function AdminStoreOrdersPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  await requireAdmin();
  const params = await searchParams;
  const status: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const [rows, pendingCount] = await Promise.all([
    listOrdersForAdmin(status),
    countPendingOrders(),
  ]);

  const columns: Column<(typeof rows)[number]>[] = [
    {
      key: "order",
      header: "Order",
      cell: (o) => (
        <div className="min-w-0">
          <Link
            href={`/admin/store/orders/${o.id}`}
            className="font-mono text-[13px] font-bold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {o.orderNumber}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">
            {o.customerName} · {o.customerEmail}
          </div>
        </div>
      ),
    },
    {
      key: "total",
      header: "Total",
      cell: (o) => formatMinor(o.totalMinor, o.currency),
      className: "whitespace-nowrap font-semibold",
    },
    {
      key: "status",
      header: "Status",
      cell: (o) => (
        <StatusBadge label={STATUS_PRETTY[o.status] ?? o.status} dot />
      ),
    },
    {
      key: "placed",
      header: "Placed",
      cell: (o) => (
        <span className="text-[12px] text-[var(--color-slate)]">
          {formatAdminDateTime(o.createdAt)}
        </span>
      ),
      className: "whitespace-nowrap",
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (o) => (
        <Link
          href={`/admin/store/orders/${o.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Manage →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Commerce"
        title="Store orders"
        lede="Every order placed on the OrthoGlobe Store. Issue invoices, mark paid, ship, and track delivery from here."
      />
      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-3">
        <KpiCard
          label="Pending invoice"
          value={pendingCount}
          tone="amber"
          Icon={ShoppingBag}
        />
        <KpiCard label="On this page" value={rows.length} tone="ink" />
        <KpiCard
          label="Completed"
          value={rows.filter((r) => r.status === "delivered").length}
          tone="emerald"
        />
      </div>
      <div className="mb-4">
        <Toolbar>
          {STATUS_FILTERS.map((s) => (
            <FilterPill
              key={s}
              href={`/admin/store/orders${s === "all" ? "" : `?status=${s}`}`}
              label={s === "all" ? "all" : STATUS_PRETTY[s]}
              active={status === s}
            />
          ))}
        </Toolbar>
      </div>
      {rows.length === 0 ? (
        <EmptyState
          Icon={ShoppingBag}
          title="No orders yet"
          description="Orders placed on /products/store/checkout will appear here."
        />
      ) : (
        <DataTable columns={columns} rows={rows} rowKey={(o) => o.id} />
      )}
    </>
  );
}
