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;
  amount: number | null;
  currency: string | null;
  payment_date: string | null;
  mode: string | null;
  reference: string | null;
  application: { applicant_name: string | null } | { applicant_name: string | null }[] | null;
  branch: { name: string | null } | { name: string | null }[] | null;
}

const columns: ReportColumn[] = [
  { key: "date", label: "Date" },
  { key: "applicant", label: "Applicant" },
  { key: "branch", label: "Branch" },
  { key: "amount", label: "Amount", numeric: true },
  { key: "currency", label: "Currency" },
  { key: "mode", label: "Mode" },
  { key: "reference", label: "Reference" },
];

export default async function Page() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("fee_payments")
    .select(
      "id, amount, currency, payment_date, mode, reference, application:student_applications(applicant_name), branch:branches(name)",
    )
    .order("payment_date", { ascending: false });

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

  const rows = payments.map((p) => ({
    date: p.payment_date,
    applicant: one(p.application)?.applicant_name ?? null,
    branch: one(p.branch)?.name ?? null,
    amount: p.amount ?? 0,
    currency: p.currency,
    mode: p.mode,
    reference: p.reference,
  }));

  const total = payments.reduce((sum, p) => sum + (p.amount ?? 0), 0);

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