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 BillingHistoryPage() {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const invoices = await prisma.billingInvoice.findMany({
    where: { tenantId: session.tenantId },
    orderBy: { dueDate: "desc" }
  });

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