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

export default async function AdminDashboardPage() {
  const [productCount, orderCount, paidOrders, recentOrders] = await Promise.all([
    prisma.product.count(),
    prisma.order.count(),
    prisma.order.findMany({ where: { status: "paid" } }),
    prisma.order.findMany({ orderBy: { createdAt: "desc" }, take: 5 }),
  ]);

  const revenue = paidOrders.reduce((sum, o) => sum + o.total, 0);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Dashboard</h1>

      {!isRazorpayConfigured() && (
        <div className="mt-4 rounded-md bg-amber-50 px-4 py-3 text-sm text-amber-800">
          Razorpay isn&apos;t configured — checkout runs in demo mode (no real payment is taken). Add
          <code className="mx-1">RAZORPAY_KEY_ID</code> and <code className="mx-1">RAZORPAY_KEY_SECRET</code> to <code>.env</code>.
        </div>
      )}

      <div className="mt-6 grid grid-cols-3 gap-4">
        <Stat label="Products" value={String(productCount)} />
        <Stat label="Orders" value={String(orderCount)} />
        <Stat label="Revenue (paid)" value={formatPaise(revenue)} />
      </div>

      <div className="mt-8">
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-semibold text-stone-700">Recent orders</h2>
          <Link href="/iv-manage-84x2/orders" className="text-sm text-rose-700 hover:underline">View all</Link>
        </div>
        <div className="mt-3 overflow-hidden rounded-lg border border-rose-100 bg-white">
          {recentOrders.length === 0 ? (
            <p className="p-4 text-sm text-stone-500">No orders yet.</p>
          ) : (
            <table className="w-full text-sm">
              <tbody className="divide-y divide-rose-100">
                {recentOrders.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>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-rose-100 bg-white p-4">
      <div className="text-xs text-stone-500">{label}</div>
      <div className="mt-1 text-xl font-semibold text-stone-800">{value}</div>
    </div>
  );
}
