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

const CONVERSION_STATUSES = new Set(["Visa Approved", "Travelled"]);

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

  const [{ data: users }, { data: assignments }, { data: applications }] =
    await Promise.all([
      supabase.from("users").select("id, full_name").order("full_name"),
      supabase.from("lead_assignments").select("user_id"),
      supabase
        .from("student_applications")
        .select("counselor_id, status"),
    ]);

  type Acc = {
    name: string;
    assigned: number;
    applications: number;
    conversions: number;
  };

  const byUser = new Map<string, Acc>();
  for (const u of users ?? []) {
    byUser.set(u.id, {
      name: u.full_name ?? "—",
      assigned: 0,
      applications: 0,
      conversions: 0,
    });
  }

  const ensure = (id: string | null): Acc | null => {
    if (!id) return null;
    let acc = byUser.get(id);
    if (!acc) {
      acc = { name: "Unknown", assigned: 0, applications: 0, conversions: 0 };
      byUser.set(id, acc);
    }
    return acc;
  };

  for (const a of assignments ?? []) {
    const acc = ensure(a.user_id);
    if (acc) acc.assigned += 1;
  }

  for (const app of applications ?? []) {
    const acc = ensure(app.counselor_id);
    if (!acc) continue;
    acc.applications += 1;
    if (app.status && CONVERSION_STATUSES.has(app.status as string)) {
      acc.conversions += 1;
    }
  }

  const columns: ReportColumn[] = [
    { key: "counselor", label: "Counselor" },
    { key: "assigned", label: "Leads Assigned", numeric: true },
    { key: "applications", label: "Applications", numeric: true },
    { key: "conversions", label: "Conversions", numeric: true },
  ];

  const rows = Array.from(byUser.values()).map((u) => ({
    counselor: u.name,
    assigned: u.assigned,
    applications: u.applications,
    conversions: u.conversions,
  }));

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