import { formatAmount, formatMsat } from './format';
import { useAmountUnit } from './useAmountUnit';

// One place amounts are rendered, so the sats/BTC toggle flips every number on screen at once.
//
// `sats` is a number; `msat` is a decimal STRING and stays one all the way through formatMsat. Passing a
// msat through the `sats` prop would parse it into a double — which is exactly the bug the string type
// exists to prevent, so the two props are deliberately not interchangeable.

type AmountProps = {
  sats?: number | null;
  msat?: string | null;
  className?: string;
  /** Colour a negative amount as a spend and a positive one as a receipt. */
  signed?: boolean;
};

export const Amount = ({ sats, msat, className = '', signed = false }: AmountProps) => {
  const { unit } = useAmountUnit();
  const text = msat !== undefined ? formatMsat(msat, unit) : formatAmount(sats, unit);

  const tone = !signed || sats == null ? '' : sats < 0 ? 'text-destructive' : sats > 0 ? 'text-emerald-500' : '';

  return (
    <span className={`tabular-nums ${tone} ${className}`}>
      {signed && sats != null && sats > 0 ? '+' : ''}
      {text}
    </span>
  );
};

/** The toggle itself — a button, because it mutates a preference rather than navigating. */
export const UnitToggle = ({ className = '' }: { className?: string }) => {
  const { unit, toggle } = useAmountUnit();

  return (
    <button
      type="button"
      onClick={toggle}
      title="Switch between satoshis and BTC"
      className={`rounded-md border border-border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition-colors hover:bg-muted hover:text-foreground ${className}`}
    >
      {unit === 'sats' ? 'sats' : 'BTC'}
    </button>
  );
};
