import { useTranslation } from "react-i18next";
import { HelpCircle } from "lucide-react";
import KpiSparkline from "./KpiSparkline";
import type { CartesKpi, CartesKpiId } from "../../../shared/types";

export interface KpiCardProps {
  id: CartesKpiId;
  title: string;
  kpi: CartesKpi;
  format: "currency" | "percent";
  /** When true, positive deltas are rendered in red (e.g. rising expenses). */
  deltaIsBadWhenUp?: boolean;
  /** Optional help text shown on hover of a (?) icon next to the title. */
  tooltip?: string;
}

function formatCurrency(amount: number, language: string): string {
  return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
    style: "currency",
    currency: "CAD",
    maximumFractionDigits: 0,
  }).format(amount);
}

function formatPercent(value: number, language: string, signed = false): string {
  return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
    style: "percent",
    maximumFractionDigits: 1,
    signDisplay: signed ? "always" : "auto",
  }).format(value / 100);
}

function formatValue(value: number, format: "currency" | "percent", language: string): string {
  return format === "currency" ? formatCurrency(value, language) : formatPercent(value, language);
}

function formatDeltaAbs(
  value: number,
  format: "currency" | "percent",
  language: string,
): string {
  if (format === "currency") {
    return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
      style: "currency",
      currency: "CAD",
      maximumFractionDigits: 0,
      signDisplay: "always",
    }).format(value);
  }
  // Savings rate delta in percentage points — not a % of %
  const formatted = new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
    maximumFractionDigits: 1,
    signDisplay: "always",
  }).format(value);
  return `${formatted} pt`;
}

interface DeltaBadgeProps {
  abs: number | null;
  pct: number | null;
  label: string;
  format: "currency" | "percent";
  language: string;
  deltaIsBadWhenUp: boolean;
}

function DeltaBadge({ abs, pct, label, format, language, deltaIsBadWhenUp }: DeltaBadgeProps) {
  if (abs === null) {
    return (
      <div className="flex flex-col items-start">
        <span className="text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
          {label}
        </span>
        <span className="text-xs text-[var(--muted-foreground)] italic">—</span>
      </div>
    );
  }
  const isUp = abs >= 0;
  const isBad = deltaIsBadWhenUp ? isUp : !isUp;
  // Treat near-zero as neutral
  const isNeutral = abs === 0;
  const colorClass = isNeutral
    ? "text-[var(--muted-foreground)]"
    : isBad
      ? "text-[var(--negative)]"
      : "text-[var(--positive)]";
  const absText = formatDeltaAbs(abs, format, language);
  const pctText = pct === null ? "" : ` (${formatPercent(pct, language, true)})`;
  return (
    <div className="flex flex-col items-start">
      <span className="text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
        {label}
      </span>
      <span className={`text-xs font-medium tabular-nums ${colorClass}`}>
        {absText}
        {pctText}
      </span>
    </div>
  );
}

export default function KpiCard({
  id,
  title,
  kpi,
  format,
  deltaIsBadWhenUp = false,
  tooltip,
}: KpiCardProps) {
  const { t, i18n } = useTranslation();
  const language = i18n.language;

  return (
    <div
      data-kpi={id}
      className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4 flex flex-col gap-3"
    >
      <div className="text-sm text-[var(--muted-foreground)] flex items-center gap-1">
        <span>{title}</span>
        {tooltip && (
          <span
            title={tooltip}
            aria-label={tooltip}
            className="inline-flex items-center text-[var(--muted-foreground)] cursor-help"
          >
            <HelpCircle size={12} aria-hidden="true" />
          </span>
        )}
      </div>
      <div className="text-2xl font-bold tabular-nums text-[var(--foreground)]">
        {kpi.current === null ? "—" : formatValue(kpi.current, format, language)}
      </div>
      <KpiSparkline data={kpi.sparkline} />
      <div className="flex items-start justify-between gap-2 pt-1 border-t border-[var(--border)]">
        <DeltaBadge
          abs={kpi.deltaMoMAbs}
          pct={kpi.deltaMoMPct}
          label={t("reports.cartes.deltaMoMLabel")}
          format={format}
          language={language}
          deltaIsBadWhenUp={deltaIsBadWhenUp}
        />
        <DeltaBadge
          abs={kpi.deltaYoYAbs}
          pct={kpi.deltaYoYPct}
          label={t("reports.cartes.deltaYoYLabel")}
          format={format}
          language={language}
          deltaIsBadWhenUp={deltaIsBadWhenUp}
        />
      </div>
    </div>
  );
}
