import { cn } from '@/lib/cn'

type BarDatum = {
  label: string
  value: number
  sublabel?: string
}

type Props = {
  data: BarDatum[]
  maxBars?: number
  formatValue?: (v: number) => string
  barClassName?: string
}

// Horizontal bar chart using plain Tailwind — không cần thư viện ngoài.
export function BarChart({ data, maxBars = 12, formatValue = v => v.toLocaleString('vi-VN'), barClassName }: Props) {
  const shown = data.slice(0, maxBars)
  const max = Math.max(1, ...shown.map(d => d.value))

  return (
    <div className="space-y-1.5">
      {shown.length === 0 && <div className="py-6 text-center text-sm text-slate-400">Chưa có dữ liệu</div>}
      {shown.map((d, i) => {
        const pct = (d.value / max) * 100
        return (
          <div key={i} className="group">
            <div className="flex items-center justify-between text-xs text-slate-600">
              <span className="truncate pr-2">{d.label}</span>
              <span className="font-mono tabular-nums">{formatValue(d.value)}</span>
            </div>
            <div className="h-2 rounded-full bg-slate-100">
              <div
                className={cn('h-full rounded-full bg-brand-500 transition-all group-hover:bg-brand-600', barClassName)}
                style={{ width: `${pct}%` }}
              />
            </div>
            {d.sublabel && <div className="mt-0.5 text-[10px] text-slate-400">{d.sublabel}</div>}
          </div>
        )
      })}
    </div>
  )
}
