import { ArrowDown, ArrowUp, Minus } from "lucide-react"
import { cn } from "@/shared/lib/utils"

/** 对比变化方向 */
export type ComparisonTrend = "up" | "down" | "flat"

/** 对比计算结果 */
export interface ComparisonResult {
  /** 当前值 */
  current: number
  /** 上一周期值 */
  previous: number
  /** 变化百分比（-100 到 +∞） */
  changePercent: number
  /** 趋势方向 */
  trend: ComparisonTrend
}

/**
 * 计算两个周期的变化百分比（L3 纯函数，便于单测）。
 *
 * - 上一周期为 0 且当前 > 0：返回 +100（新增）
 * - 上一周期为 0 且当前为 0：返回 0（持平）
 * - 正常情况：(current - previous) / previous * 100
 */
export function computeComparison(current: number, previous: number): ComparisonResult {
  if (previous === 0) {
    return {
      current,
      previous,
      changePercent: current > 0 ? 100 : 0,
      trend: current > 0 ? "up" : "flat",
    }
  }

  const changePercent = ((current - previous) / Math.abs(previous)) * 100
  const trend: ComparisonTrend =
    Math.abs(changePercent) < 0.01 ? "flat" : changePercent > 0 ? "up" : "down"

  return { current, previous, changePercent, trend }
}

/**
 * 数据对比徽章组件（L3）。
 *
 * 显示当前值与上一周期的变化百分比，带方向图标和颜色。
 * 用于仪表盘统计卡片旁的对比指示。
 */
export function ComparisonBadge({
  result,
  className,
}: {
  result: ComparisonResult
  className?: string
}) {
  const { changePercent, trend } = result
  const absPercent = Math.abs(Math.round(changePercent))

  const trendConfig = {
    up: { icon: ArrowUp, color: "text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30" },
    down: { icon: ArrowDown, color: "text-red-600 bg-red-50 dark:bg-red-950/30" },
    flat: { icon: Minus, color: "text-muted-foreground bg-muted/50" },
  } as const

  const config = trendConfig[trend]
  const Icon = config.icon

  return (
    <span
      className={cn(
        "inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-xs font-medium tabular-nums",
        config.color,
        className,
      )}
      role="status"
      aria-label={`Change: ${absPercent}% ${trend}`}
    >
      <Icon className="h-3 w-3" aria-hidden />
      {absPercent}%
    </span>
  )
}
