import { getRegionCodes, getRegionLabel } from "@/lib/regions";
import { getAvailableDataRange } from "@/lib/reports/data-range";
import { isValidMonth, listMonths } from "@/lib/reports/month";
import { buildRegionSummary, regionEmailStats, regionEmailSubject, suggestedRegionSummaryBullets } from "@/lib/reports/region-summary";
import { RegionSummaryClient } from "@/components/admin/region-summary-client";

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

  const regionCodes = getRegionCodes();
  const dataRange = await getAvailableDataRange();
  const availableMonths = dataRange ? listMonths(dataRange.earliest, dataRange.latest) : [];

  const region = rawRegion && regionCodes.includes(rawRegion) ? rawRegion : (regionCodes[0] ?? "");
  const month = rawMonth && isValidMonth(rawMonth) ? rawMonth : (availableMonths[0] ?? "");

  if (!region || !month) {
    return (
      <RegionSummaryClient
        regionCodes={regionCodes}
        availableMonths={availableMonths}
        region={region}
        month={month}
        regionLabel=""
        monthLabel=""
        subject=""
        suggestedBullets={[]}
        trend={[]}
        countryTable={[]}
        countriesWithoutActivity={[]}
        productSplit={[]}
        stats={[]}
      />
    );
  }

  const summary = await buildRegionSummary(region, month);
  const suggestedBullets = suggestedRegionSummaryBullets(summary);

  return (
    <RegionSummaryClient
      regionCodes={regionCodes}
      availableMonths={availableMonths}
      region={region}
      month={month}
      regionLabel={getRegionLabel(region)}
      monthLabel={summary.monthLabel}
      subject={regionEmailSubject(summary)}
      suggestedBullets={suggestedBullets}
      stats={regionEmailStats(summary)}
      trend={summary.trend}
      countryTable={summary.countryTable}
      countriesWithoutActivity={summary.countriesWithoutActivity}
      productSplit={summary.productSplit}
    />
  );
}
