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 CommissionRow {
  id: string;
  amount: number | null;
  currency: string | null;
  status: string | null;
  received_date: string | null;
  institute: { name: string | null } | { name: string | null }[] | null;
  application: { applicant_name: string | null } | { applicant_name: string | null }[] | null;
}

const columns: ReportColumn[] = [
  { key: "institute", label: "Institute" },
  { key: "applicant", label: "Applicant" },
  { key: "amount", label: "Amount", numeric: true },
  { key: "currency", label: "Currency" },
  { key: "status", label: "Status" },
  { key: "received_date", label: "Received Date" },
];

export default async function Page() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("university_commissions")
    .select(
      "id, amount, currency, status, received_date, institute:institutes(name), application:student_applications(applicant_name)",
    )
    .order("received_date", { ascending: false });

  const commissions = (data ?? []) as CommissionRow[];

  const rows = commissions.map((c) => ({
    institute: one(c.institute)?.name ?? null,
    applicant: one(c.application)?.applicant_name ?? null,
    amount: c.amount ?? 0,
    currency: c.currency,
    status: c.status,
    received_date: c.received_date,
  }));

  const received = commissions
    .filter((c) => (c.status ?? "").toLowerCase() === "received")
    .reduce((sum, c) => sum + (c.amount ?? 0), 0);
  const pending = commissions
    .filter((c) => (c.status ?? "").toLowerCase() === "pending")
    .reduce((sum, c) => sum + (c.amount ?? 0), 0);

  return (
    <ReportTable
      title="University Commission Report"
      breadcrumb="Home / Reports / University Commission"
      columns={columns}
      rows={rows}
      footerNote={`Received: ${received.toLocaleString()} · Pending: ${pending.toLocaleString()}`}
    />
  );
}
