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

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

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

export default async function SuperAdminSettingsPage() {
  const session = await getSession();
  if (!session || session.role !== "super_admin") {
    return (
      <ShellPage shell="super-admin" title="Platform Settings" description="Pricing config, feature flags, dan template policy config.">
        <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">Akses super-admin diperlukan.</p>
      </ShellPage>
    );
  }

  const [tenantCountByStatus, planCount, lastInvoiceDate, channelStatus] = await Promise.all([
    prisma.tenant.groupBy({
      by: ["status"],
      _count: { _all: true }
    }),
    prisma.subscriptionPlan.count(),
    prisma.billingInvoice.findFirst({
      orderBy: { createdAt: "desc" },
      select: { createdAt: true }
    }),
    prisma.channel.groupBy({
      by: ["status"],
      _count: { _all: true }
    })
  ]);

  const modules = [
    {
      name: "Subscription plans",
      purpose: "Plan catalog dan metadata harga",
      route: "/super-admin/billing/plans",
      status: `${planCount} plans`
    },
    {
      name: "Tenant management",
      purpose: "Pengelolaan tenant, status, dan limit",
      route: "/super-admin/tenants",
      status: `${tenantCountByStatus.reduce((acc, item) => acc + item._count._all, 0)} tenants`
    },
    {
      name: "Channel registry",
      purpose: "Provider channel dan health status",
      route: "/super-admin/channels",
      status: `Connected: ${channelStatus.find((item) => item.status === "CONNECTED")?._count._all ?? 0}`
    },
    {
      name: "Webhook logs",
      purpose: "Monitoring event provider",
      route: "/super-admin/webhook-logs",
      status: "Realtime stream"
    },
    {
      name: "Template policy",
      purpose: "Approval dan pembatasan template",
      route: "/templates",
      status: "Review by tenant"
    },
    {
      name: "Invoice monitoring",
      purpose: "Status pembayaran tenant",
      route: "/super-admin/billing/invoices",
      status: lastInvoiceDate ? `Last: ${formatDate(lastInvoiceDate.createdAt)}` : "No invoices"
    }
  ];

  return (
    <ShellPage shell="super-admin" title="Platform Settings" description="Overview setting-platform berdasarkan data operasional real-time.">
      <TablePlaceholder
        title="Platform settings modules"
        columns={["Module", "Purpose", "Route", "Status"]}
        rows={modules.map((module) => [
          module.name,
          module.purpose,
          <Link key={`${module.name}-route`} href={module.route} className="text-brand hover:underline">
            {module.route}
          </Link>,
          module.status
        ])}
      />
    </ShellPage>
  );
}
