import styles from './KpiStrip.module.css'
import { Sparkline } from '../../primitives/Sparkline/Sparkline'
import type { CSSProperties, ReactNode } from 'react'

export interface KpiItem {
  label: string
  value: string | number
  trend?: { label: ReactNode; variant?: 'success' | 'warning' | 'error' | 'muted' }
  subtitle?: string
  sparkline?: number[]
  borderColor?: string
}

export interface KpiStripProps {
  items: KpiItem[]
  className?: string
}

const trendClassMap: Record<string, string> = {
  success: styles.trendSuccess,
  warning: styles.trendWarning,
  error: styles.trendError,
  muted: styles.trendMuted,
}

export function KpiStrip({ items, className }: KpiStripProps) {
  const stripClasses = [styles.kpiStrip, className ?? ''].filter(Boolean).join(' ')
  const gridStyle: CSSProperties = {
    gridTemplateColumns: items.length > 0 ? `repeat(${items.length}, 1fr)` : undefined,
  }

  return (
    <div className={stripClasses} style={gridStyle}>
      {items.map((item) => {
        const borderColor = item.borderColor ?? 'var(--amber)'
        const cardStyle: CSSProperties & Record<string, string> = {
          '--kpi-border-color': borderColor,
        }
        const trendVariant = item.trend?.variant ?? 'muted'
        const trendClass = trendClassMap[trendVariant] ?? styles.trendMuted

        return (
          <div key={item.label} className={styles.kpiCard} style={cardStyle}>
            <div className={styles.label}>{item.label}</div>
            <div className={styles.valueRow}>
              <span className={styles.value}>{item.value}</span>
              {item.trend && (
                <span className={`${styles.trend} ${trendClass}`}>
                  {item.trend.label}
                </span>
              )}
            </div>
            {item.subtitle && (
              <div className={styles.subtitle}>{item.subtitle}</div>
            )}
            {item.sparkline && item.sparkline.length >= 2 && (
              <div className={styles.sparkline}>
                <Sparkline
                  data={item.sparkline}
                  color={borderColor}
                  width={200}
                  height={32}
                />
              </div>
            )}
          </div>
        )
      })}
    </div>
  )
}
