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

/** Embeds may arrive as an array (Supabase) — normalize to the first element. */
function one<T>(v: T | T[] | null | undefined): T | null {
  if (Array.isArray(v)) return v[0] ?? null;
  return v ?? null;
}

interface FeePaymentRow {
  id: string;
  student_application_id: string | null;
  amount: number | null;
  application: { applicant_name: string | null } | { applicant_name: string | null }[] | null;
  branch: { name: string | null } | { name: string | null }[] | null;
}

interface Agg {
  applicant: string | null;
  branch: string | null;
  count: number;
  total: number;
}

const columns: ReportColumn[] = [
  { key: "applicant", label: "Applicant" },
  { key: "branch", label: "Branch" },
  { key: "count", label: "Payments Count", numeric: true },
  { key: "total", label: "Total Collected", numeric: true },
];

export default async function Page() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("fee_payments")
    .select(
      "id, student_application_id, amount, application:student_applications(applicant_name), branch:branches(name)",
    );

  const payments = (data ?? []) as FeePaymentRow[];

  const byApplication = new Map<string, Agg>();
  for (const p of payments) {
    const key = p.student_application_id ?? p.id;
    const existing = byApplication.get(key);
    if (existing) {
      existing.count += 1;
      existing.total += p.amount ?? 0;
    } else {
      byApplication.set(key, {
        applicant: one(p.application)?.applicant_name ?? null,
        branch: one(p.branch)?.name ?? null,
        count: 1,
        total: p.amount ?? 0,
      });
    }
  }

  const rows = Array.from(byApplication.values()).map((a) => ({
    applicant: a.applicant,
    branch: a.branch,
    count: a.count,
    total: a.total,
  }));

  const grandTotal = rows.reduce((sum, r) => sum + r.total, 0);

  return (
    <ReportTable
      title="Fee Payment Report"
      breadcrumb="Home / Reports / Fee Payment"
      columns={columns}
      rows={rows}
      footerNote={`Grand Total: ${grandTotal.toLocaleString()}`}
    />
  );
}
