import * as React from 'react';
import { TrendingUp, TrendingDown, Minus, Info } from 'lucide-react';

import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';

interface KPITileProps extends React.HTMLAttributes<HTMLDivElement> {
  title: string;
  value: React.ReactNode;
  /** Signed delta vs. prior period; positive = green, negative = red, undefined = no chip. */
  delta?: number;
  /** Optional suffix appended to the delta value (e.g. '%' for percentage deltas). */
  deltaSuffix?: string;
  /** Pre-rendered sparkline (recharts) - caller decides shape. */
  sparkline?: React.ReactNode;
  /** Optional accent stripe colour token; defaults to brand. */
  accent?: 'brand' | 'success' | 'warning' | 'mint' | 'teal' | 'purple';
  /** Optional explainer rendered in a Popover when the user clicks the (i)
   *  icon next to the title. Keep it short - one sentence ideally. */
  tooltip?: React.ReactNode;
  /** For metrics where lower is better (bounce rate, error count). The
   *  delta number is still shown verbatim, but the colour flips: a
   *  negative delta renders green (improvement) instead of red. */
  lowerIsBetter?: boolean;
}

const ACCENT_STRIPES: Record<NonNullable<KPITileProps['accent']>, string> = {
  brand: 'bg-gradient-brand',
  success: 'bg-success',
  warning: 'bg-warning',
  mint: 'bg-mint',
  teal: 'bg-teal',
  purple: 'bg-purple',
};

export function KPITile({
  title,
  value,
  delta,
  deltaSuffix,
  sparkline,
  accent = 'brand',
  tooltip,
  lowerIsBetter = false,
  className,
  ...props
}: KPITileProps) {
  // Colour logic is independent of the displayed number. For normal
  // metrics, positive=good (green); for `lowerIsBetter` metrics, flip so
  // a drop renders green.
  const isImprovement = typeof delta === 'number' ? (lowerIsBetter ? delta < 0 : delta > 0) : false;
  const isRegression = typeof delta === 'number' ? (lowerIsBetter ? delta > 0 : delta < 0) : false;
  const deltaClass =
    typeof delta !== 'number'
      ? ''
      : isImprovement
        ? 'text-success'
        : isRegression
          ? 'text-error'
          : 'text-muted-foreground';
  const deltaPrefix = typeof delta === 'number' ? (delta > 0 ? '+' : '') : '';

  return (
    <div
      data-testid="kpi-tile"
      className={cn(
        'group relative overflow-hidden rounded-xl border border-border bg-gradient-brand-soft p-3 shadow-sm transition-all duration-base ease-smooth hover:shadow-md sm:p-5',
        className,
      )}
      {...props}
    >
      <div className={cn('absolute inset-x-0 top-0 h-1', ACCENT_STRIPES[accent])} aria-hidden />
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0">
          <div className="flex items-center gap-1 text-xs font-medium uppercase tracking-wide text-muted-foreground sm:text-xs">
            <span>{title}</span>
            {tooltip ? (
              <Popover>
                <PopoverTrigger
                  type="button"
                  aria-label={`What is ${title}?`}
                  className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-400"
                >
                  <Info className="size-3" aria-hidden />
                </PopoverTrigger>
                <PopoverContent
                  align="start"
                  className="w-64 text-xs leading-relaxed normal-case tracking-normal text-muted-foreground"
                >
                  {tooltip}
                </PopoverContent>
              </Popover>
            ) : null}
          </div>
          <div className="mt-1 flex items-baseline gap-2 sm:mt-2">
            <span className="truncate text-lg font-semibold tabular-nums text-foreground sm:text-2xl">
              {value}
            </span>
            {typeof delta === 'number' ? (
              <span
                className={cn(
                  'inline-flex shrink-0 items-center gap-0.5 text-xs font-medium',
                  deltaClass,
                )}
              >
                {delta > 0 ? (
                  <TrendingUp className="size-3" aria-hidden />
                ) : delta < 0 ? (
                  <TrendingDown className="size-3" aria-hidden />
                ) : (
                  <Minus className="size-3" aria-hidden />
                )}
                {deltaPrefix}
                {delta}
                {deltaSuffix ?? ''}
              </span>
            ) : null}
          </div>
        </div>
        {sparkline ? <div className="h-12 w-24 shrink-0 opacity-80">{sparkline}</div> : null}
      </div>
    </div>
  );
}
