import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cva } from 'class-variance-authority'
import { cn } from './utils'

const iconVariants = cva('flex items-center justify-center rounded-lg shrink-0', {
  variants: {
    tone: {
      amber: 'bg-amber-10 text-[var(--color-amber-text)]',
      cyan: 'bg-cyan-10 text-[var(--color-cyan-text)]',
      emerald: 'bg-emerald-10 text-[var(--color-emerald-text)]',
      violet: 'bg-violet-10 text-[var(--color-violet-text)]',
      rose: 'bg-rose-10 text-[var(--color-rose-text)]',
      orange: 'bg-primary/15 text-[var(--color-primary-text)]',
      glass: 'bg-foreground/[0.08] text-foreground-secondary',
    },
    size: {
      sm: 'h-8 w-8 [&>svg]:size-4',
      md: 'h-9 w-9 [&>svg]:size-5',
      lg: 'h-10 w-10 [&>svg]:size-5',
    },
  },
  defaultVariants: { tone: 'glass', size: 'md' },
})

export type MetricCardTone = 'amber' | 'cyan' | 'emerald' | 'violet' | 'rose' | 'orange' | 'glass'

export interface DashboardMetricCardProps extends HTMLAttributes<HTMLDivElement> {
  icon?: ReactNode
  label: string
  value: string | number
  detail?: string
  trend?: ReactNode
  tone?: MetricCardTone
  iconSize?: 'sm' | 'md' | 'lg'
}

const DashboardMetricCard = forwardRef<HTMLDivElement, DashboardMetricCardProps>(
  (
    { icon, label, value, detail, trend, tone = 'glass', iconSize = 'md', className, ...props },
    ref
  ) => (
    <div
      ref={ref}
      className={cn(
        'flex flex-col gap-3 rounded-xl border border-border-glass bg-glass p-4',
        className
      )}
      {...props}
    >
      <div className="flex items-start justify-between">
        <p className="text-foreground-tertiary text-[10px] font-semibold tracking-wider uppercase">
          {label}
        </p>
        {icon && <div className={iconVariants({ tone, size: iconSize })}>{icon}</div>}
      </div>
      <p className="text-foreground text-2xl font-bold tabular-nums">{value}</p>
      {(detail || trend) && (
        <div className="flex items-center gap-2">
          {detail && <span className="text-foreground-secondary text-sm">{detail}</span>}
          {trend && <span className="text-xs font-semibold">{trend}</span>}
        </div>
      )}
    </div>
  )
)
DashboardMetricCard.displayName = 'DashboardMetricCard'

export { DashboardMetricCard, iconVariants as metricIconVariants }
