import type { Metadata } from "next";
import Link from "next/link";

import { OrderStatusBadge } from "@/components/orders/order-status-badge";
import { GlassCard } from "@/components/shared/glass-card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { orderItemSummary } from "@/lib/orders/presentation";
import { listOrdersPage } from "@/lib/db/store";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Admin · Transactions",
  robots: { index: false, follow: false },
};

function pageFromSearchParams(value: string | string[] | undefined) {
  const raw = Array.isArray(value) ? value[0] : value;
  const page = Number(raw ?? "1");
  return Number.isFinite(page) ? Math.max(1, Math.floor(page)) : 1;
}

function pageHref(page: number) {
  return `/admin/orders?page=${page}`;
}

export default async function AdminOrdersPage({
  searchParams,
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const result = await listOrdersPage(pageFromSearchParams(params?.page), 25);
  const orders = result.items;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="font-display text-3xl text-white">TRANSACTIONS</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          All checkout orders — matches Razorpay payments when verification or webhooks
          complete. Sign in as admin to view.
        </p>
        <p className="mt-2 text-xs text-muted-foreground">
          Showing {orders.length} of {result.total} orders.
        </p>
      </div>
      <GlassCard className="overflow-x-auto p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Order ID</TableHead>
              <TableHead>Customer</TableHead>
              <TableHead>Items</TableHead>
              <TableHead>Total</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Razorpay payment</TableHead>
              <TableHead>Created</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {orders.map((o) => (
              <TableRow key={o.id}>
                <TableCell className="max-w-[140px] font-mono text-xs">{o.id}</TableCell>
                <TableCell>{o.userEmail}</TableCell>
                <TableCell className="max-w-[200px] text-xs text-muted-foreground">
                  {orderItemSummary(o)}
                </TableCell>
                <TableCell>₹{o.totalInr}</TableCell>
                <TableCell>
                  <OrderStatusBadge status={o.status} />
                </TableCell>
                <TableCell className="font-mono text-xs text-muted-foreground">
                  {o.razorpayPaymentId ?? "—"}
                </TableCell>
                <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                  {new Date(o.createdAt).toLocaleString()}
                </TableCell>
              </TableRow>
            ))}
            {orders.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground">
                  No transactions yet.
                </TableCell>
              </TableRow>
            ) : null}
          </TableBody>
        </Table>
      </GlassCard>
      {result.totalPages > 1 ? (
        <div className="flex items-center justify-between text-sm">
          <Link
            href={pageHref(Math.max(1, result.page - 1))}
            aria-disabled={result.page <= 1}
            className="rounded-lg border border-white/10 px-3 py-2 text-muted-foreground aria-disabled:pointer-events-none aria-disabled:opacity-40"
          >
            Previous
          </Link>
          <span className="text-muted-foreground">
            Page {result.page} of {result.totalPages}
          </span>
          <Link
            href={pageHref(Math.min(result.totalPages, result.page + 1))}
            aria-disabled={result.page >= result.totalPages}
            className="rounded-lg border border-white/10 px-3 py-2 text-muted-foreground aria-disabled:pointer-events-none aria-disabled:opacity-40"
          >
            Next
          </Link>
        </div>
      ) : null}
    </div>
  );
}
