import { ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";

function formatDate(date: Date | null | undefined) {
  if (!date) {
    return "-";
  }

  return new Intl.DateTimeFormat("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric"
  }).format(date);
}

export default async function SuperAdminSubscriptionsPage() {
  const session = await getSession();
  if (!session || session.role !== "super_admin") {
    redirect("/unauthorized");
  }

  const tenants = await prisma.tenant.findMany({
    include: {
      plan: true,
      billingInvoices: {
        take: 1,
        orderBy: { dueDate: "desc" },
        select: { dueDate: true, paymentStatus: true }
      },
      _count: {
        select: { users: true }
      }
    },
    orderBy: { createdAt: "desc" }
  });

  return (
    <ShellPage shell="super-admin" title="Tenant Subscriptions" description="Plan aktif, usage, dan payment status lintas tenant.">
      <TablePlaceholder
        title="Subscriptions"
        columns={["Tenant", "Plan", "Usage", "Renewal", "Payment"]}
        rows={tenants.map((tenant) => [
          tenant.name,
          tenant.plan.name,
          `${tenant._count.users}/${tenant.plan.seatQuota}`,
          formatDate(tenant.billingInvoices[0]?.dueDate),
          tenant.billingInvoices[0]?.paymentStatus ?? "No invoice"
        ])}
      />
    </ShellPage>
  );
}
