"use client";

import { CircleHelp } from "lucide-react";

import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

export type ConvertedTotalBreakdown = {
  currency: string;
  total: number;
  exchangeRate: number | null;
  convertedTotal: number | null;
};

function formatPlain(value: number | null, decimals = 0) {
  if (value === null || !Number.isFinite(value)) return "—";
  return value.toLocaleString("en-US", {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  });
}

/**
 * Converted reporting-currency total with FX breakdown tooltip
 * (Accumulator + Structured Product parity).
 */
export function ConvertedTotalValueWithTooltip({
  value,
  currencyCode,
  breakdowns,
}: {
  value: number | null;
  currencyCode?: string | null;
  breakdowns?: ConvertedTotalBreakdown[];
}) {
  const formatted = formatPlain(value, 2);
  if (!breakdowns || breakdowns.length === 0) {
    return <span>{formatted}</span>;
  }

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <button
          type="button"
          className="inline-flex items-center gap-1 text-inherit underline decoration-dotted underline-offset-2"
        >
          <span>{formatted}</span>
          <CircleHelp className="size-3.5 text-muted-foreground" />
        </button>
      </TooltipTrigger>
      <TooltipContent side="top" align="end" className="max-w-[320px] text-xs leading-relaxed">
        <div className="space-y-2">
          <p className="font-medium">
            Converted total{currencyCode ? ` (${currencyCode})` : ""}
          </p>
          <div className="space-y-2">
            {breakdowns.map((entry) => (
              <div key={entry.currency} className="grid grid-cols-[52px_1fr] gap-x-3">
                <span className="font-semibold">{entry.currency}</span>
                <div className="text-muted-foreground">
                  <div>Total: {formatPlain(entry.total, 2)}</div>
                  <div>
                    Rate: {entry.exchangeRate === null ? "N/A" : formatPlain(entry.exchangeRate, 6)}
                  </div>
                  <div className="pt-0.5 text-primary-foreground">
                    <span className="font-medium">Converted:</span>{" "}
                    <span className="font-semibold">
                      {entry.convertedTotal === null ? "N/A" : formatPlain(entry.convertedTotal, 2)}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </TooltipContent>
    </Tooltip>
  );
}
