import { ArrowDownRight, ArrowUpRight, Minus } from 'lucide-react';

import { percentDelta } from '@/lib/money';
import { cn } from '@/lib/utils';

/** Delta pill versus the previous period. */
export function TrendDelta({ current, previous }: { current: number; previous: number | null }) {
  const delta = previous === null ? null : percentDelta(current, previous);
  if (delta === null) {
    return (
      <span className="inline-flex items-center gap-1 rounded-pill bg-surface-muted px-2 py-0.5 text-caption font-semibold text-muted-foreground">
        <Minus className="h-3 w-3" aria-hidden="true" />
        <span className="sr-only">No comparison</span>
      </span>
    );
  }
  const rounded = Math.round(delta * 10) / 10;
  const up = rounded > 0;
  const down = rounded < 0;
  const Icon = up ? ArrowUpRight : down ? ArrowDownRight : Minus;
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 rounded-pill px-2 py-0.5 text-caption font-semibold tabular-nums',
        up && 'bg-success-soft text-success',
        down && 'bg-danger-soft text-danger',
        !up && !down && 'bg-surface-muted text-muted-foreground',
      )}
    >
      <Icon className="h-3 w-3" aria-hidden="true" />
      {up ? '+' : ''}
      {rounded}%
    </span>
  );
}
