import { getViewerContext } from "@/lib/auth";
import { getClmDashboardData, getClmWorkbookSnapshot } from "@/lib/clm-dashboard";
import { resolveDashboardScope } from "@/lib/dashboard-request";
import { fetchDashboardData } from "@/lib/queries/dashboard";
import { getAvailableDataRange } from "@/lib/reports/data-range";
import { CLM_MIN_CALLS_FOR_LEADERBOARD, buildClmInsight, buildTakeaways, buildVaeInsight } from "@/lib/reports/insights";
import { addMonths, isValidMonth, listMonths, monthBounds, previousMonth } from "@/lib/reports/month";
import { getClmTrend } from "@/lib/clm-trend";
import { readScorecard } from "@/lib/clm-scorecard";
import { MonthlyReportView } from "@/components/reports/monthly-report-view";

// How much history the report's trend charts show, ending at the report month.
const TRAILING_MONTHS = 12;

export default async function ReportsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const viewer = await getViewerContext();
  const params = await searchParams;
  const rawMonth = Array.isArray(params.month) ? params.month[0] : params.month;
  const rawScope = Array.isArray(params.scope) ? params.scope[0] : params.scope;

  const dataRange = await getAvailableDataRange();
  const availableMonths = dataRange ? listMonths(dataRange.earliest, dataRange.latest) : [];
  const month = rawMonth && isValidMonth(rawMonth) ? rawMonth : (availableMonths[0] ?? "");

  const { activeScope, scopeCountries, adminCountryOptions } = resolveDashboardScope(
    viewer,
    rawScope ?? "",
  );

  if (!month) {
    return (
      <MonthlyReportView
        month=""
        availableMonths={[]}
        activeScope={activeScope}
        vae={null}
        clm={null}
        takeaways={[]}
        vaeInsight={null}
        clmInsight={null}
        trendSeries={[]}
        presentationTrends={{}}
        officialClmRate={undefined}
      />
    );
  }

  const { from, to } = monthBounds(month);
  const previous = monthBounds(previousMonth(month));
  const trailingFrom = monthBounds(addMonths(month, -(TRAILING_MONTHS - 1))).from;

  const [vae, vaePrevious, vaeTrailing, clm, clmPrevious, clmTrailingWorkbook, scorecard] = await Promise.all([
    fetchDashboardData(viewer, { from, to }, scopeCountries, adminCountryOptions),
    fetchDashboardData(viewer, previous, scopeCountries, adminCountryOptions),
    fetchDashboardData(viewer, { from: trailingFrom, to }, scopeCountries, adminCountryOptions),
    getClmDashboardData({ from, to }, scopeCountries),
    getClmDashboardData(previous, scopeCountries),
    // Ends at the report month so each deck's trend is measured against the
    // month before it, not against whatever is latest in the dataset.
    getClmWorkbookSnapshot({ from: trailingFrom, to }, scopeCountries),
    readScorecard(),
  ]);

  const vaeInsight = buildVaeInsight(vae, vaePrevious);
  const clmInsight = buildClmInsight(clm, clmPrevious, CLM_MIN_CALLS_FOR_LEADERBOARD);
  const takeaways = buildTakeaways({
    scopeLabel: activeScope || "Overall",
    vae: vaeInsight,
    clm: clmInsight,
  });

  const presentationTrends = Object.fromEntries(
    clmTrailingWorkbook.presentationSlides.map((row) => [
      row.presentation,
      getClmTrend(row.monthlyCalls ?? []),
    ]),
  );

  return (
    <MonthlyReportView
      month={month}
      availableMonths={availableMonths}
      activeScope={activeScope}
      vae={vae}
      clm={clm}
      takeaways={takeaways}
      vaeInsight={vaeInsight}
      clmInsight={clmInsight}
      trendSeries={vaeTrailing.monthlySeries}
      presentationTrends={presentationTrends}
      officialClmRate={scorecard[month]}
    />
  );
}
