import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise } from "@/lib/format";
import StatusBadge from "@/components/admin/StatusBadge";

export default async function AdminOrdersPage({
  searchParams,
}: {
  searchParams: Promise<{ email?: string }>;
}) {
  const { email } = await searchParams;
  const orders = await prisma.order.findMany({
    where: email ? { email } : undefined,
    orderBy: { createdAt: "desc" },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Orders</h1>
      {email && (
        <p className="mt-1 text-sm text-stone-500">
          Filtered to <span className="font-medium text-stone-700">{email}</span> —{" "}
          <Link href="/iv-manage-84x2/orders" className="text-rose-700 hover:underline">
            clear filter
          </Link>
        </p>
      )}

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {orders.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No orders yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Order</th>
                <th className="p-3">Customer</th>
                <th className="p-3">Total</th>
                <th className="p-3">Status</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {orders.map((o) => (
                <tr key={o.id}>
                  <td className="p-3">
                    <Link href={`/iv-manage-84x2/orders/${o.id}`} className="font-medium text-rose-700 hover:underline">
                      {o.orderNumber}
                    </Link>
                  </td>
                  <td className="p-3 text-stone-600">{o.customerName}</td>
                  <td className="p-3 text-stone-600">{formatPaise(o.total)}</td>
                  <td className="p-3"><StatusBadge status={o.status} /></td>
                  <td className="p-3 text-stone-500">{o.createdAt.toLocaleDateString("en-IN")}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
