"use client";

import { KPICard } from "@/components/ui/kpi-card";
import { formatMoney, formatPct } from "@/components/sales-targets/sales-targets-helpers";

export type SalesTargetsSummaryData = {
  teamCount: number;
  teamsWithTarget: number;
  totalTarget: number;
  totalAttained: number;
  avgPct: number | null;
};

function attainedPctOfTarget(summary: SalesTargetsSummaryData): number | null {
  if (summary.totalTarget <= 0) return null;
  return (summary.totalAttained / summary.totalTarget) * 100;
}

export function SalesTargetsSummary({
  monthLabel,
  summary,
}: {
  monthLabel: string;
  summary: SalesTargetsSummaryData;
}) {
  const attainedPct = attainedPctOfTarget(summary);

  const kpis = [
    {
      label: "Teams",
      value: String(summary.teamCount),
      subtext: `active in ${monthLabel}`,
    },
    {
      label: "Total Team Target",
      value: formatMoney(summary.totalTarget),
      subtext:
        summary.teamsWithTarget > 0
          ? `${summary.teamsWithTarget} team${summary.teamsWithTarget === 1 ? "" : "s"} · ae + support`
          : "no team targets set yet",
    },
    {
      label: "AE Attained",
      value: formatMoney(summary.totalAttained),
      subtext:
        attainedPct != null
          ? `${formatPct(attainedPct)} of total team target`
          : "first paid in month · no team targets set",
      isUp: attainedPct != null ? attainedPct >= 100 : true,
    },
    {
      label: "Average Progress",
      value: summary.avgPct != null ? formatPct(summary.avgPct) : "—",
      subtext: "mean across teams with data",
      isUp: (summary.avgPct ?? 0) >= 100,
    },
  ];

  return (
    <section aria-label="Period summary">
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {kpis.map((kpi) => (
          <KPICard
            key={kpi.label}
            label={kpi.label}
            value={kpi.value}
            isUp={kpi.isUp ?? true}
            subtext={kpi.subtext}
          />
        ))}
      </div>
    </section>
  );
}
