import type { AppsFlyerDailyFunnelResponse } from "@/lib/daily-control-cards";

type Aggregate = Record<string, number | null> | undefined;

const number = (total: Aggregate, key: string) => typeof total?.[key] === "number" ? Number(total[key]) : 0;
const clicks = (total: Aggregate) => {
  const explicitTotal = total?.total_paid_clicks;
  return typeof explicitTotal === "number" ? explicitTotal : number(total, "meta_clicks") + number(total, "google_clicks");
};
const compact = new Intl.NumberFormat("fr-FR", { notation: "compact", maximumFractionDigits: 1 });
const integer = new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 0 });

export function PaidMediaFunnel({ response }: { response: AppsFlyerDailyFunnelResponse }) {
  const currentTotal = response.total;
  const previousTotal = response.previous?.total;
  const stages = [
    { label: "Dépense", current: number(currentTotal, "total_spend"), previous: number(previousTotal, "total_spend"), money: true, next: "Impressions" },
    { label: "Impressions", current: number(currentTotal, "total_paid_impressions"), previous: number(previousTotal, "total_paid_impressions"), next: "Clics" },
    { label: "Clics sur le lien", current: clicks(currentTotal), previous: clicks(previousTotal), next: "Installs" },
    { label: "Installs", current: number(currentTotal, "appsflyer_installs_total"), previous: number(previousTotal, "appsflyer_installs_total"), next: "Démarrages onboarding" },
    { label: "Démarrages onboarding", current: number(currentTotal, "onboarding_start_active_users"), previous: number(previousTotal, "onboarding_start_active_users"), next: "Réussites onboarding" },
    { label: "Réussites onboarding", current: number(currentTotal, "onboarding_success_active_users"), previous: number(previousTotal, "onboarding_success_active_users") },
  ];
  const formatValue = (value: number, money = false) => `${compact.format(value)}${money ? " MAD" : ""}`;

  return <article className="paidMediaFunnelCard">
    <header><p>Parcours d’acquisition payante</p><h3>Paid Media Acquisition Funnel</h3><span>Dépense → Impressions → Clics → Installs → Démarrage → Réussite</span></header>
    <div className="paidMediaTableScroll"><table className="paidMediaTable">
      <thead><tr><th>Étape du funnel</th><th>Valeur actuelle</th><th>Période précédente</th><th>vs période précédente</th><th>Conversion vers l’étape suivante</th></tr></thead>
      <tbody>{stages.map((stage, index) => {
        const variation = stage.previous > 0 ? (stage.current - stage.previous) / stage.previous * 100 : null;
        const nextStage = stages[index + 1];
        const conversion = index > 0 && nextStage && stage.current > 0 ? nextStage.current / stage.current * 100 : null;
        const highlighted = index === stages.length - 1;
        return <tr key={stage.label} className={highlighted ? "finalObjective" : ""}>
          <td>{stage.label}</td><td>{formatValue(stage.current, stage.money)}</td><td>{formatValue(stage.previous, stage.money)}</td>
          <td>{variation === null ? <span className="funnelUnavailable">—</span> : <span className={variation >= 0 ? "funnelUp" : "funnelDown"}>{variation >= 0 ? "↑" : "↓"} {Math.abs(variation).toFixed(1)}%</span>}</td>
          <td>{conversion === null || !stage.next ? "—" : <><b>{conversion < .1 ? conversion.toFixed(2) : conversion.toFixed(1)}%</b><small>{stage.label} → {stage.next}</small></>}</td>
        </tr>;
      })}</tbody>
    </table></div>
    <footer>Valeurs agrégées sur les périodes sélectionnées · {integer.format(stages.at(-1)?.current ?? 0)} réussites onboarding sur la période actuelle.</footer>
  </article>;
}

export function CostEfficiencyMetrics({ response, currentCdc, previousCdc }: { response: AppsFlyerDailyFunnelResponse; currentCdc: number | null; previousCdc: number | null }) {
  const currentTotal = response.total;
  const previousTotal = response.previous?.total;
  const ratio = (numerator: number, denominator: number, multiplier = 1) => denominator > 0 ? numerator / denominator * multiplier : null;
  const spend = number(currentTotal, "total_spend");
  const previousSpend = number(previousTotal, "total_spend");
  const rows = [
    { label: "CPM", current: ratio(spend, number(currentTotal, "total_paid_impressions"), 1_000), previous: ratio(previousSpend, number(previousTotal, "total_paid_impressions"), 1_000) },
    { label: "CPC", current: ratio(spend, clicks(currentTotal)), previous: ratio(previousSpend, clicks(previousTotal)) },
    { label: "CPI", current: ratio(spend, number(currentTotal, "appsflyer_installs_total")), previous: ratio(previousSpend, number(previousTotal, "appsflyer_installs_total")) },
    { label: "Coût / démarrage onboarding", current: ratio(spend, number(currentTotal, "onboarding_start_active_users")), previous: ratio(previousSpend, number(previousTotal, "onboarding_start_active_users")) },
    { label: "Coût / réussite onboarding", current: ratio(spend, number(currentTotal, "onboarding_success_active_users")), previous: ratio(previousSpend, number(previousTotal, "onboarding_success_active_users")), highlighted: true },
    { label: "Coût / CDC", current: ratio(spend, currentCdc ?? 0), previous: ratio(previousSpend, previousCdc ?? 0), highlighted: true },
  ];
  const money = (value: number | null) => value === null ? "N/A" : `${integer.format(value)} MAD`;

  return <article className="paidMediaFunnelCard costEfficiencyCard">
    <header><p>Efficacité des coûts</p><h3>Cost Efficiency Metrics</h3><span>Coût d’acquisition à chaque étape du funnel, comparé à la période précédente.</span></header>
    <div className="paidMediaTableScroll"><table className="paidMediaTable costEfficiencyTable">
      <thead><tr><th>Indicateur de coût</th><th>Coût actuel</th><th>Coût période précédente</th><th>vs période précédente</th></tr></thead>
      <tbody>{rows.map((row) => {
        const variation = row.current !== null && row.previous !== null && row.previous > 0 ? (row.current - row.previous) / row.previous * 100 : null;
        return <tr key={row.label} className={row.highlighted ? "finalObjective" : ""}><td>{row.label}</td><td>{money(row.current)}</td><td>{money(row.previous)}</td><td>{variation === null ? <span className="funnelUnavailable">—</span> : <span className={variation <= 0 ? "funnelUp" : "funnelDown"}>{variation <= 0 ? "↓" : "↑"} {Math.abs(variation).toFixed(1)}%</span>}</td></tr>;
      })}</tbody>
    </table></div>
  </article>;
}
