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

const OFFER_STATUSES = new Set([
  "Offer Received",
  "Visa Applied",
  "Visa Approved",
  "Visa Rejected",
  "Travelled",
]);

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

  const [{ data: branches }, { data: leads }, { data: applications }] =
    await Promise.all([
      supabase.from("branches").select("id, name").order("name"),
      supabase.from("leads").select("branch_id"),
      supabase
        .from("student_applications")
        .select("branch_id, status, offer_received"),
    ]);

  type Acc = {
    name: string;
    leads: number;
    applications: number;
    offers: number;
    visaApproved: number;
    travelled: number;
  };

  const byBranch = new Map<string, Acc>();
  for (const b of branches ?? []) {
    byBranch.set(b.id, {
      name: b.name,
      leads: 0,
      applications: 0,
      offers: 0,
      visaApproved: 0,
      travelled: 0,
    });
  }

  const ensure = (id: string | null): Acc => {
    const key = id ?? "__none__";
    let acc = byBranch.get(key);
    if (!acc) {
      acc = {
        name: id ? "Unknown" : "Unassigned",
        leads: 0,
        applications: 0,
        offers: 0,
        visaApproved: 0,
        travelled: 0,
      };
      byBranch.set(key, acc);
    }
    return acc;
  };

  for (const l of leads ?? []) {
    ensure(l.branch_id).leads += 1;
  }

  for (const a of applications ?? []) {
    const acc = ensure(a.branch_id);
    acc.applications += 1;
    const status = a.status as string | null;
    if (a.offer_received || (status && OFFER_STATUSES.has(status))) {
      acc.offers += 1;
    }
    if (status === "Visa Approved" || status === "Travelled") {
      acc.visaApproved += 1;
    }
    if (status === "Travelled") {
      acc.travelled += 1;
    }
  }

  const columns: ReportColumn[] = [
    { key: "branch", label: "Branch" },
    { key: "leads", label: "Leads", numeric: true },
    { key: "applications", label: "Applications", numeric: true },
    { key: "offers", label: "Offers", numeric: true },
    { key: "visaApproved", label: "Visa Approved", numeric: true },
    { key: "travelled", label: "Travelled", numeric: true },
  ];

  const knownIds = new Set((branches ?? []).map((b) => b.id));
  const rows = Array.from(byBranch.entries())
    // keep every real branch; only keep the synthetic Unknown/Unassigned bucket if it has data
    .filter(([id, b]) => knownIds.has(id) || b.leads || b.applications)
    .map(([, b]) => ({
      branch: b.name,
      leads: b.leads,
      applications: b.applications,
      offers: b.offers,
      visaApproved: b.visaApproved,
      travelled: b.travelled,
    }));

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