import { cn, formatNumber } from '@/lib/utils'

interface MetricCardProps {
  title: string
  value: string | number | null | undefined
  unit?: string
  format?: 'number' | 'percent' | 'currency' | 'text'
  trend?: number
  description?: string
  className?: string
  status?: 'good' | 'warn' | 'bad'
}

const STATUS_STYLES: Record<string, string> = {
  good: 'border-green-200 bg-green-50/40 border-l-4 border-l-green-500',
  warn: 'border-yellow-200 bg-yellow-50/40 border-l-4 border-l-yellow-500',
  bad: 'border-red-200 bg-red-50/40 border-l-4 border-l-red-500',
}

const STATUS_VALUE_STYLES: Record<string, string> = {
  good: 'text-green-700',
  warn: 'text-yellow-700',
  bad: 'text-red-700',
}

export function MetricCard({ title, value, unit, format = 'number', trend, description, className, status }: MetricCardProps) {
  const displayValue = format === 'percent'
    ? value === null || value === undefined ? '-' : `${Number(value).toFixed(2)}%`
    : format === 'currency'
    ? value === null || value === undefined ? '-' : `¥${formatNumber(value)}`
    : format === 'text'
    ? (value || '-')
    : formatNumber(value)

  return (
    <div className={cn('rounded-lg border bg-card p-4 shadow-sm', status && STATUS_STYLES[status], className)}>
      <div className="flex items-center gap-1">
        <p className="text-sm text-muted-foreground">{title}</p>
        {description && (
          <span className="group relative inline-flex">
            <span className="flex h-4 w-4 cursor-help items-center justify-center rounded-full bg-muted text-[10px] text-muted-foreground">?</span>
            <span className="pointer-events-none absolute left-1/2 top-6 z-10 w-48 -translate-x-1/2 rounded-md bg-gray-800 px-3 py-2 text-xs text-white opacity-0 transition-opacity group-hover:opacity-100">
              {description}
            </span>
          </span>
        )}
      </div>
      <div className="mt-2 flex items-baseline gap-1">
        <span className={cn('text-2xl font-bold', status && STATUS_VALUE_STYLES[status])}>{displayValue}</span>
        {unit && <span className="text-sm text-muted-foreground">{unit}</span>}
      </div>
      {trend !== undefined && (
        <p className={cn('mt-1 text-xs', trend > 0 ? 'text-green-600' : 'text-red-600')}>
          {trend > 0 ? '↑' : '↓'} {Math.abs(trend).toFixed(1)}% <span className="text-muted-foreground">环比上周</span>
        </p>
      )}
    </div>
  )
}
