import { redirect } from "next/navigation";

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

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

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

function formatMoney(value: number) {
  return new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
    maximumFractionDigits: 0
  }).format(value);
}

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

  const invoices = await prisma.billingInvoice.findMany({
    include: { tenant: true, plan: true },
    orderBy: { createdAt: "desc" }
  });

  return (
    <ShellPage shell="super-admin" title="Invoices" description="Invoice seluruh tenant.">
      <TablePlaceholder
        title="Invoices"
        columns={["Invoice", "Tenant", "Period", "Amount", "Status"]}
        rows={invoices.map((invoice) => [
          <Link
            key={`${invoice.id}-invoice`}
            href={`/super-admin/billing/invoices/${invoice.id}`}
            className="text-brand hover:underline"
          >
            {invoice.invoiceNumber}
          </Link>,
          invoice.tenant.name,
          `${formatDate(invoice.periodStart)} - ${formatDate(invoice.periodEnd)} (${invoice.plan.name})`,
          formatMoney(invoice.totalAmount),
          invoice.paymentStatus
        ])}
      />
    </ShellPage>
  );
}
