import Link from "next/link";
import { prisma } from "@/lib/db";
import { formatPrice, formatDateTime } from "@/lib/format";
import { OrderStatusBadge } from "@/components/order/OrderDetails";
import { REPAIR_STATUS_META, type RepairStatus } from "@/lib/constants";

export const dynamic = "force-dynamic";

export default async function AdminDashboard() {
  const [
    activeProducts,
    outOfStock,
    pendingOrders,
    totalOrders,
    newSellRequests,
    newRepairs,
    activeRepairs,
    recentOrders,
    recentRepairs,
    revenueAgg,
  ] = await Promise.all([
    prisma.product.count({ where: { status: "ACTIVE" } }),
    prisma.product.count({ where: { status: "ACTIVE", quantity: { lte: 0 } } }),
    prisma.order.count({ where: { status: "PENDING" } }),
    prisma.order.count(),
    prisma.sellRequest.count({ where: { status: "NEW" } }),
    prisma.repairBooking.count({ where: { status: "NEW" } }),
    prisma.repairBooking.count({
      where: { status: { in: ["NEW", "SCHEDULED", "IN_PROGRESS"] } },
    }),
    prisma.order.findMany({
      orderBy: { createdAt: "desc" },
      take: 6,
      include: { items: true },
    }),
    prisma.repairBooking.findMany({
      orderBy: { createdAt: "desc" },
      take: 6,
      include: { service: true, technician: true },
    }),
    prisma.order.aggregate({
      _sum: { total: true },
      where: { status: { in: ["CONFIRMED", "SHIPPED", "READY_FOR_PICKUP", "DELIVERED"] } },
    }),
  ]);

  const stats = [
    { label: "Active products", value: activeProducts, href: "/admin/products", icon: "📦" },
    { label: "Pending orders", value: pendingOrders, href: "/admin/orders?status=PENDING", icon: "🕒" },
    { label: "New repairs", value: newRepairs, href: "/admin/repairs?status=NEW", icon: "🛠️" },
    { label: "New sell requests", value: newSellRequests, href: "/admin/sell-requests?status=NEW", icon: "💰" },
  ];

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        {stats.map((s) => (
          <Link
            key={s.label}
            href={s.href}
            className="rounded-xl border border-slate-200 bg-white p-4 transition hover:shadow-sm"
          >
            <div className="flex items-center justify-between">
              <span className="text-2xl">{s.icon}</span>
              <span className="text-2xl font-bold text-slate-900">{s.value}</span>
            </div>
            <p className="mt-1 text-sm text-slate-500">{s.label}</p>
          </Link>
        ))}
      </div>

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <p className="text-sm text-slate-500">Total orders</p>
          <p className="text-xl font-bold text-slate-900">{totalOrders}</p>
        </div>
        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <p className="text-sm text-slate-500">Confirmed revenue</p>
          <p className="text-xl font-bold text-slate-900">
            {formatPrice(revenueAgg._sum.total ?? 0)}
          </p>
        </div>
        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <p className="text-sm text-slate-500">Active repairs</p>
          <p className="text-xl font-bold text-slate-900">{activeRepairs}</p>
        </div>
        <div className="rounded-xl border border-slate-200 bg-white p-4">
          <p className="text-sm text-slate-500">Out of stock (active)</p>
          <p className="text-xl font-bold text-slate-900">{outOfStock}</p>
        </div>
      </div>

      <div className="rounded-xl border border-slate-200 bg-white">
        <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
          <h2 className="font-bold text-slate-900">Recent orders</h2>
          <Link href="/admin/orders" className="text-sm text-brand-600 hover:underline">
            View all →
          </Link>
        </div>
        {recentOrders.length === 0 ? (
          <p className="px-4 py-8 text-center text-sm text-slate-400">
            No orders yet.
          </p>
        ) : (
          <div className="divide-y divide-slate-100">
            {recentOrders.map((o) => (
              <Link
                key={o.id}
                href={`/admin/orders/${o.id}`}
                className="flex items-center justify-between gap-3 px-4 py-3 text-sm hover:bg-slate-50"
              >
                <div className="min-w-0">
                  <p className="font-semibold text-slate-800">{o.orderNumber}</p>
                  <p className="truncate text-xs text-slate-500">
                    {o.customerName} • {o.items.length} item(s) •{" "}
                    {formatDateTime(o.createdAt)}
                  </p>
                </div>
                <div className="flex shrink-0 items-center gap-3">
                  <span className="font-semibold">{formatPrice(o.total)}</span>
                  <OrderStatusBadge status={o.status} />
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>

      <div className="rounded-xl border border-slate-200 bg-white">
        <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
          <h2 className="font-bold text-slate-900">Recent repair bookings</h2>
          <Link href="/admin/repairs" className="text-sm text-brand-600 hover:underline">
            View all →
          </Link>
        </div>
        {recentRepairs.length === 0 ? (
          <p className="px-4 py-8 text-center text-sm text-slate-400">
            No repair bookings yet.
          </p>
        ) : (
          <div className="divide-y divide-slate-100">
            {recentRepairs.map((r) => (
              <Link
                key={r.id}
                href={`/admin/repairs/${r.id}`}
                className="flex items-center justify-between gap-3 px-4 py-3 text-sm hover:bg-slate-50"
              >
                <div className="min-w-0">
                  <p className="font-semibold text-slate-800">{r.bookingNumber}</p>
                  <p className="truncate text-xs text-slate-500">
                    {r.customerName} • {r.service?.name ?? "General"} •{" "}
                    {r.technician?.name ?? "Unassigned"}
                  </p>
                </div>
                <span
                  className={`shrink-0 rounded-full px-2 py-0.5 text-xs font-semibold ${
                    REPAIR_STATUS_META[r.status as RepairStatus]?.className ??
                    "bg-slate-100 text-slate-600"
                  }`}
                >
                  {REPAIR_STATUS_META[r.status as RepairStatus]?.label ?? r.status}
                </span>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
