import { createClient } from "@/lib/supabase/server";
import { ReportTable } from "@/components/reports/report-table";
import type { ReportColumn } from "@/lib/types";

export default async function Page() {
  const supabase = await createClient();

  const { data: applications } = await supabase
    .from("student_applications")
    .select("created_at");

  // Bucket by calendar day, keeping a sortable ISO key alongside the display label.
  const counts = new Map<string, { label: string; count: number }>();
  for (const a of applications ?? []) {
    if (!a.created_at) continue;
    const d = new Date(a.created_at as string);
    const key = d.toISOString().slice(0, 10);
    const entry = counts.get(key) ?? { label: d.toLocaleDateString(), count: 0 };
    entry.count += 1;
    counts.set(key, entry);
  }

  const columns: ReportColumn[] = [
    { key: "date", label: "Date" },
    { key: "admissions", label: "Admissions", numeric: true },
  ];

  const rows = Array.from(counts.entries())
    .sort((a, b) => (a[0] < b[0] ? 1 : -1))
    .map(([, v]) => ({ date: v.label, admissions: v.count }));

  return (
    <ReportTable
      title="Day-wise Admission Report"
      breadcrumb="Home / Reports / Day-wise Admission"
      columns={columns}
      rows={rows}
    />
  );
}
