import * as React from 'react'

export interface SparklineTrendProps {
  data: number[]
  color?: string
  height?: number
  className?: string
}

// Map common Tailwind color class suffixes to hex values
const COLOR_MAP: Record<string, string> = {
  'blue-500': '#3B82F6',
  'green-500': '#10B981',
  'purple-500': '#A855F7',
  'emerald-500': '#10B981',
  'red-500': '#EF4444',
  'orange-500': '#F97316',
  'yellow-500': '#EAB308',
  'indigo-500': '#6366F1',
  'pink-500': '#EC4899',
  'primary-500': '#3B82F6',
  'primary-600': '#2563EB',
  'accent-500': '#A855F7',
  'success-500': '#10B981',
}

function resolveColor(color: string): string {
  // If it looks like a hex/rgb value already, use it directly
  if (color.startsWith('#') || color.startsWith('rgb')) return color

  // Strip common Tailwind prefixes like "text-"
  const key = color.replace(/^text-/, '')
  return COLOR_MAP[key] || COLOR_MAP['blue-500']
}

export function SparklineTrend({
  data,
  color = 'blue-500',
  height = 40,
  className,
}: SparklineTrendProps) {
  if (data.length < 2) return null

  const width = 100
  const padding = 2

  const min = Math.min(...data)
  const max = Math.max(...data)
  const range = max - min || 1

  const points = data.map((value, index) => {
    const x = (index / (data.length - 1)) * width
    const y = height - ((value - min) / range) * (height - padding * 2) - padding
    return `${x},${y}`
  })

  const pathData = `M ${points.join(' L ')}`
  const areaData = `${pathData} L ${width},${height} L 0,${height} Z`

  const hexColor = resolveColor(color)
  const gradientId = `sparkline-gradient-${React.useId().replace(/:/g, '')}`

  const trend =
    data[data.length - 1] > data[0]
      ? 'increasing'
      : data[data.length - 1] < data[0]
        ? 'decreasing'
        : 'stable'

  return (
    <svg
      width="100%"
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="none"
      className={className ?? 'w-full'}
      role="img"
      aria-label={`Trend chart showing ${trend} pattern`}
    >
      <defs>
        <linearGradient id={gradientId} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={hexColor} stopOpacity="0.3" />
          <stop offset="100%" stopColor={hexColor} stopOpacity="0.05" />
        </linearGradient>
      </defs>
      <path
        d={areaData}
        fill={`url(#${gradientId})`}
        className="transition-all duration-300"
      />
      <path
        d={pathData}
        fill="none"
        stroke={hexColor}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        className="transition-all duration-300"
      />
    </svg>
  )
}
