import {prisma} from "@/lib/db/prisma";
import Link from "next/link";

function StatCard({
  title,
  value,
  sub,
  href,
  iconBg = "bg-gray-50",
  iconColor = "text-gray-600"
}: {
  title: string;
  value: string | number;
  sub?: string;
  href?: string;
  iconBg?: string;
  iconColor?: string;
}) {
  const card = (
    <div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 cursor-pointer">
      <p className="text-xs font-semibold uppercase tracking-wide text-gray-400">{title}</p>
      <p className={`mt-2 text-3xl font-bold ${iconColor}`}>{value}</p>
      {sub && <p className="mt-1 text-xs text-gray-400">{sub}</p>}
    </div>
  );
  return href ? <Link href={href}>{card}</Link> : card;
}

function MiniBar({label, value, max, color = "bg-indigo-500"}: {label: string; value: number; max: number; color?: string}) {
  const pct = max > 0 ? Math.round((value / max) * 100) : 0;
  return (
    <div className="flex items-center gap-3">
      <span className="w-24 shrink-0 truncate text-sm text-gray-600">{label}</span>
      <div className="flex-1 rounded-full bg-gray-100 h-2.5">
        <div className={`h-2.5 rounded-full ${color} transition-all`} style={{width: `${pct}%`}} />
      </div>
      <span className="w-8 text-right text-xs font-semibold text-gray-700">{value}</span>
    </div>
  );
}

export default async function SuperAdminDashboardPage() {
  const [tenants, bookings, payments, users] = await Promise.all([
    prisma.tenant.findMany({orderBy: {createdAt: "desc"}, take: 5}),
    prisma.booking.findMany({select: {status: true, totalAmount: true, currency: true}}),
    prisma.paymentTransaction.findMany({where: {status: "PAID"}, select: {amount: true, currency: true}}),
    prisma.user.count()
  ]);

  const totalTenants = await prisma.tenant.count();
  const activeTenants = await prisma.tenant.count({where: {status: "ACTIVE"}});
  const totalRevenue = payments.reduce((sum, p) => sum + Number(p.amount), 0);
  const confirmedBookings = bookings.filter((b) => !["CANCELLED", "DRAFT", "REJECTED"].includes(b.status)).length;

  const tenantStatusCount: Record<string, number> = {};
  for (const t of await prisma.tenant.findMany({select: {status: true}})) {
    tenantStatusCount[t.status] = (tenantStatusCount[t.status] ?? 0) + 1;
  }

  return (
    <div className="space-y-7 p-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Platform Overview</h1>
        <p className="mt-1 text-gray-500">Real-time statistics across all tenants</p>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <StatCard
          title="Total Tenants"
          value={totalTenants}
          sub={`${activeTenants} active`}
          href="/super-admin/tenants"
          iconColor="text-violet-700"
        />
        <StatCard
          title="Total Bookings"
          value={bookings.length}
          sub={`${confirmedBookings} confirmed`}
          iconColor="text-indigo-700"
        />
        <StatCard
          title="Platform Revenue"
          value={`$${totalRevenue.toFixed(0)}`}
          sub="All paid transactions"
          iconColor="text-emerald-700"
        />
        <StatCard
          title="Registered Users"
          value={users}
          iconColor="text-gray-900"
        />
      </div>

      {/* Charts + Recent */}
      <div className="grid gap-6 lg:grid-cols-2">
        <div className="rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-gray-900">Tenants by Status</h2>
          <div className="space-y-3.5">
            {Object.entries(tenantStatusCount).map(([status, count]) => (
              <MiniBar
                key={status}
                label={status}
                value={count}
                max={totalTenants}
                color={
                  status === "ACTIVE" ? "bg-emerald-500" :
                  status === "TRIAL" ? "bg-indigo-500" :
                  status === "SUSPENDED" ? "bg-red-500" : "bg-gray-400"
                }
              />
            ))}
          </div>
        </div>

        <div className="rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
          <h2 className="mb-5 font-semibold text-gray-900">Recent Tenants</h2>
          <ul className="divide-y divide-gray-50">
            {tenants.map((t) => (
              <li key={t.id} className="py-3">
                <Link
                  href={`/super-admin/tenants/${t.id}`}
                  className="flex items-center justify-between hover:text-indigo-600 transition-colors group"
                >
                  <div>
                    <p className="font-medium text-gray-900 group-hover:text-indigo-700 transition-colors">{t.name}</p>
                    <p className="text-xs text-gray-400 mt-0.5">{t.email}</p>
                  </div>
                  <span
                    className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                      t.status === "ACTIVE" ? "bg-emerald-100 text-emerald-700" :
                      t.status === "TRIAL" ? "bg-indigo-100 text-indigo-700" :
                      "bg-red-100 text-red-700"
                    }`}
                  >
                    {t.status}
                  </span>
                </Link>
              </li>
            ))}
          </ul>
          <Link href="/super-admin/tenants" className="mt-4 block text-sm text-indigo-600 hover:text-indigo-700 font-medium">
            View all tenants →
          </Link>
        </div>
      </div>
    </div>
  );
}
