/* KpiCard — primary unit of the operations dashboard.
 *
 *   ┌────────────────────────────────────┐
 *   │ LABEL                              │
 *   │ 1,247          ▲ 12 vs yesterday   │
 *   │ optional caption                    │
 *   └────────────────────────────────────┘
 *
 * Numerics use the .num-xl utility (Plex Mono, tabular-nums, large).
 * Tone "accent" gets a 2px Wulf-blue left border.
 * Tone "warn" gets the destructive border when value > 0. */

import Link from 'next/link';
import { ArrowRight, ArrowUpRight, ArrowDownRight, Minus } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Card, CardContent } from '@/components/ui/card';

export type KpiTone = 'default' | 'accent' | 'warn' | 'attention';

interface KpiDelta {
  /** Numeric delta (+ for up, - for down). */
  value: number;
  /** Suffix shown after the delta. e.g. "vs yesterday". */
  label?: string;
  /** When true, "down" is good (e.g., SLA breaches). */
  invertedSentiment?: boolean;
}

interface KpiCardProps {
  label: string;
  /** Display value. number formatted with locale, string passed through. null → em-dash. */
  value: number | string | null | undefined;
  delta?: KpiDelta;
  caption?: React.ReactNode;
  tone?: KpiTone;
  href?: string;
  loading?: boolean;
}

const TONE_STYLES: Record<KpiTone, string> = {
  default:   'border-l-transparent',
  accent:    'border-l-primary',
  warn:      'border-l-amber-500',
  attention: 'border-l-destructive',
};

export function KpiCard({
  label,
  value,
  delta,
  caption,
  tone = 'default',
  href,
  loading = false,
}: KpiCardProps) {
  const display =
    value === null || value === undefined
      ? '—'
      : typeof value === 'number'
        ? value.toLocaleString()
        : value;

  const inner = (
    <Card
      className={cn(
        'h-full border-l-2 transition-shadow',
        TONE_STYLES[tone],
        href && 'hover:shadow-sm',
      )}
    >
      <CardContent className="pt-4 pb-3 flex flex-col gap-1">
        <div className="flex items-center justify-between">
          <span className="metric-label">{label}</span>
          {href && <ArrowRight className="h-3.5 w-3.5 text-muted-foreground" />}
        </div>
        <div className="flex items-baseline gap-3">
          {loading ? (
            <span className="h-9 w-24 animate-pulse rounded bg-muted" />
          ) : (
            <span className="num-xl">{display}</span>
          )}
          {delta && !loading && <DeltaIndicator delta={delta} />}
        </div>
        {caption && !loading && (
          <div className="text-xs text-muted-foreground">{caption}</div>
        )}
      </CardContent>
    </Card>
  );

  return href ? (
    <Link href={href} className="block">
      {inner}
    </Link>
  ) : (
    inner
  );
}

function DeltaIndicator({ delta }: { delta: KpiDelta }) {
  const { value, label, invertedSentiment = false } = delta;
  if (value === 0) {
    return (
      <span className="num text-xs text-muted-foreground inline-flex items-center gap-1">
        <Minus className="h-3 w-3" />
        {label ?? 'no change'}
      </span>
    );
  }
  const positive = value > 0;
  const good = invertedSentiment ? !positive : positive;
  const colorClass = good
    ? 'text-emerald-600 dark:text-emerald-400'
    : 'text-destructive';
  const Icon = positive ? ArrowUpRight : ArrowDownRight;
  return (
    <span className={cn('num text-xs inline-flex items-center gap-1', colorClass)}>
      <Icon className="h-3 w-3" />
      {Math.abs(value)}
      {label && <span className="text-muted-foreground ml-1">{label}</span>}
    </span>
  );
}
