import { PlaceholderActions, 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) {
  if (!date) {
    return "Not synced";
  }

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

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

  const channels = await prisma.channel.findMany({
    include: { tenant: true },
    orderBy: { updatedAt: "desc" }
  });

  return (
    <ShellPage
      shell="super-admin"
      title="Channels"
      description="Connected numbers, webhook health, dan last sync."
      actions={<PlaceholderActions primaryHref="/super-admin/tenants" primaryLabel="Tenant list" />}
    >
      <TablePlaceholder
        title="Channel list"
        columns={["Number", "Tenant", "Provider", "Status", "Webhook"]}
        rows={channels.map((channel) => [
          channel.displayPhoneNumber || "N/A",
          channel.tenant.name,
          channel.provider,
          channel.status,
          `${channel.webhookStatus || "unknown"} • ${formatDate(channel.lastSyncAt)}`
        ])}
      />
    </ShellPage>
  );
}
