import { Suspense } from "react";
import { ReportsPageClient } from "@/components/reports/ReportsPageClient";
import {
  aggregateEvents,
  aggregateReport,
  parseEventDateParam,
  parseEventGroupDimension,
  parseEventSplitDimension,
  parseEventType,
  parseGroupDimension,
  parseIsoDateParam,
  parseMeasure,
  parseMode,
  parseSplitDimension,
  sumValues,
  totalForRows,
} from "@/lib/reports";
import { loadEventHistory, loadOrgLookups, loadSnapshotEmployees } from "@/lib/reports-data";
import { createClient } from "@/lib/supabase/server";

type SearchParams = {
  mode?: string;
  measure?: string;
  group?: string;
  split?: string;
  division?: string;
  location?: string;
  status?: string;
  employment?: string;
  asOf?: string;
  eventType?: string;
  from?: string;
  to?: string;
};

export default async function ReportsPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
  const params = await searchParams;
  const supabase = await createClient();
  const mode = parseMode(params.mode);

  const [{ lookups, divisions, locations }, { data: userRes }] = await Promise.all([loadOrgLookups(supabase), supabase.auth.getUser()]);
  const user = userRes.user;
  const { data: savedReports } = user
    ? await supabase.from("saved_reports").select("id, name, config").eq("created_by", user.id).order("created_at", { ascending: false })
    : { data: [] };

  if (mode === "events") {
    const group = parseEventGroupDimension(params.group);
    const split = parseEventSplitDimension(params.split);
    const eventType = parseEventType(params.eventType);
    const from = parseEventDateParam(params.from);
    const to = parseEventDateParam(params.to);

    const events = await loadEventHistory(supabase, {
      eventType: eventType ?? undefined,
      division: params.division,
      location: params.location,
      from,
      to,
    });
    const rows = aggregateEvents(events, group, split, lookups);
    const total = sumValues(rows);

    return (
      <Suspense>
        <ReportsPageClient
          mode="events"
          eventGroup={group}
          eventSplit={split ?? ""}
          eventType={eventType ?? ""}
          eventFilters={{ division: params.division ?? "", location: params.location ?? "", from: from ?? "", to: to ?? "" }}
          rows={rows}
          total={total}
          recordCount={events.length}
          divisions={divisions}
          locations={locations}
          savedReports={savedReports ?? []}
        />
      </Suspense>
    );
  }

  const measure = parseMeasure(params.measure);
  const group = parseGroupDimension(params.group);
  const split = parseSplitDimension(params.split);
  const asOf = parseIsoDateParam(params.asOf);

  const employees = await loadSnapshotEmployees(supabase, {
    division: params.division,
    location: params.location,
    status: params.status,
    employment: params.employment,
    asOf,
  });
  const rows = aggregateReport(employees, measure, group, split, lookups, asOf);
  const total = totalForRows(rows, measure);

  return (
    <Suspense>
      <ReportsPageClient
        mode="snapshot"
        measure={measure}
        group={group}
        split={split ?? ""}
        asOf={asOf ?? ""}
        filters={{
          division: params.division ?? "",
          location: params.location ?? "",
          status: params.status ?? "",
          employment: params.employment ?? "",
        }}
        rows={rows}
        total={total}
        recordCount={employees.length}
        divisions={divisions}
        locations={locations}
        savedReports={savedReports ?? []}
      />
    </Suspense>
  );
}
