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

interface BranchRow {
  id: string;
  name: string | null;
}

interface AmountRow {
  branch_id: string | null;
  amount: number | null;
}

interface AppRow {
  branch_id: string | null;
}

const columns: ReportColumn[] = [
  { key: "branch", label: "Branch" },
  { key: "applications", label: "Applications", numeric: true },
  { key: "fees", label: "Fees Collected", numeric: true },
  { key: "commission", label: "Commission", numeric: true },
];

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

  const [branchesRes, feesRes, commissionsRes, appsRes] = await Promise.all([
    supabase.from("branches").select("id, name"),
    supabase.from("fee_payments").select("branch_id, amount"),
    supabase.from("university_commissions").select("branch_id, amount"),
    supabase.from("student_applications").select("branch_id"),
  ]);

  const branches = (branchesRes.data ?? []) as BranchRow[];
  const fees = (feesRes.data ?? []) as AmountRow[];
  const commissions = (commissionsRes.data ?? []) as AmountRow[];
  const apps = (appsRes.data ?? []) as AppRow[];

  const feesByBranch = new Map<string, number>();
  for (const f of fees) {
    if (!f.branch_id) continue;
    feesByBranch.set(f.branch_id, (feesByBranch.get(f.branch_id) ?? 0) + (f.amount ?? 0));
  }

  const commissionByBranch = new Map<string, number>();
  for (const c of commissions) {
    if (!c.branch_id) continue;
    commissionByBranch.set(
      c.branch_id,
      (commissionByBranch.get(c.branch_id) ?? 0) + (c.amount ?? 0),
    );
  }

  const appsByBranch = new Map<string, number>();
  for (const a of apps) {
    if (!a.branch_id) continue;
    appsByBranch.set(a.branch_id, (appsByBranch.get(a.branch_id) ?? 0) + 1);
  }

  const rows = branches.map((b) => ({
    branch: b.name,
    applications: appsByBranch.get(b.id) ?? 0,
    fees: feesByBranch.get(b.id) ?? 0,
    commission: commissionByBranch.get(b.id) ?? 0,
  }));

  const totalApplications = rows.reduce((s, r) => s + r.applications, 0);
  const totalFees = rows.reduce((s, r) => s + r.fees, 0);
  const totalCommission = rows.reduce((s, r) => s + r.commission, 0);

  rows.push({
    branch: "TOTAL",
    applications: totalApplications,
    fees: totalFees,
    commission: totalCommission,
  });

  return (
    <ReportTable
      title="Finance Summary Report"
      breadcrumb="Home / Reports / Finance Summary"
      columns={columns}
      rows={rows}
    />
  );
}
