import type { CampaignAnalyticsResponse } from "@/lib/features/promo-code-campaigns/types";
import type { ExportSheet } from "./exportXlsx";

/**
 * Turn a CampaignAnalyticsResponse into the "Analytics" worksheets appended to
 * an export (the numbers behind the on-screen analytics card — charts are not
 * embedded). Shared by the campaign-details and member-referrals exports so
 * both produce identical sheets.
 *
 * Pass `visiblePromoCodeIds` to mirror the table/chart filters; omit it to
 * include every code. Returns [] when there's no analytics data.
 */
export function buildAnalyticsSheets(
  analytics: CampaignAnalyticsResponse | null,
  visiblePromoCodeIds?: Set<string>,
): ExportSheet[] {
  if (!analytics) return [];

  const nameById = new Map(
    analytics.promo_codes.map(
      (p) => [p.promo_code_id, p.promo_code_name] as const,
    ),
  );
  const include = (id: string) =>
    !visiblePromoCodeIds || visiblePromoCodeIds.has(id);
  const codeName = (id: string) => nameById.get(id) ?? id;

  const total = analytics.analytics.total ?? 0;
  const totalLoggedIn = analytics.analytics.totalLoggedIn ?? 0;

  const sheets: ExportSheet[] = [];

  // Sheet: signups per promo code, with a TOTAL row at the bottom.
  const perCode = analytics.analytics.byPromoCode
    .filter((r) => include(r.promo_code_id))
    .map((r) => ({
      "Promo Code": codeName(r.promo_code_id),
      Signups: r.signups ?? 0,
      "Logged In": r.logged_in ?? 0,
      "% of Total": total
        ? Number((((r.signups ?? 0) / total) * 100).toFixed(1))
        : 0,
    }))
    .sort((a, b) => b.Signups - a.Signups);
  perCode.push({
    "Promo Code": "TOTAL",
    Signups: total,
    "Logged In": totalLoggedIn,
    "% of Total": total ? 100 : 0,
  });
  sheets.push({
    sheetName: "Analytics — Signups",
    columns: [
      { key: "Promo Code", label: "Promo Code", width: 28 },
      { key: "Signups", label: "Signups", width: 12 },
      { key: "Logged In", label: "Logged In", width: 12 },
      { key: "% of Total", label: "% of Total", width: 12 },
    ],
    rows: perCode,
  });

  // Sheet: country × promo code breakdown.
  const byCountry = analytics.analytics.byCountryPromoCode
    .filter((r) => include(r.promo_code_id) && (r.signups ?? 0) > 0)
    .map((r) => ({
      Country: r.country || "—",
      "Promo Code": codeName(r.promo_code_id),
      Signups: r.signups ?? 0,
    }))
    .sort((a, b) =>
      a.Country === b.Country
        ? b.Signups - a.Signups
        : a.Country.localeCompare(b.Country),
    );
  if (byCountry.length) {
    sheets.push({
      sheetName: "Analytics — Country",
      columns: [
        { key: "Country", label: "Country", width: 22 },
        { key: "Promo Code", label: "Promo Code", width: 28 },
        { key: "Signups", label: "Signups", width: 12 },
      ],
      rows: byCountry,
    });
  }

  // Sheet: signups by day (only present on some analytics payloads).
  const byDay = analytics.analytics.byDay ?? [];
  if (byDay.length) {
    sheets.push({
      sheetName: "Analytics — By Day",
      columns: [
        { key: "Day", label: "Day", width: 16 },
        { key: "Signups", label: "Signups", width: 12 },
      ],
      rows: byDay.map((d) => ({ Day: d.day, Signups: d.signups ?? 0 })),
    });
  }

  return sheets;
}
