import type React from 'react'
import { Link } from '@tanstack/react-router'

interface HorizontalBarsRow {
  label: string
  count: number
  href?: string
}

interface HorizontalBarsProps {
  rows: HorizontalBarsRow[]
  max: number
}

export function HorizontalBars({ rows, max }: HorizontalBarsProps): React.JSX.Element {
  const safeMax = max > 0 ? max : 1

  return (
    <div>
      {rows.map((row, i) => {
        const ratio = row.count / safeMax
        const label = row.href != null ? (
          <Link
            to={row.href}
            className="mono truncate"
            style={{ fontSize: 11, color: 'var(--accent-ink)', textDecoration: 'none' }}
          >
            {row.label}
          </Link>
        ) : (
          <span className="mono truncate" style={{ fontSize: 11 }}>{row.label}</span>
        )

        return (
          <div
            key={i}
            style={{
              display: 'grid',
              gridTemplateColumns: '1fr 90px 30px',
              gap: 8,
              padding: '4px 0',
              borderBottom: i < rows.length - 1 ? '1px dotted var(--rule-2)' : 'none',
              alignItems: 'center',
            }}
          >
            {label}
            <span style={{ height: 5, background: 'var(--paper-2)', borderRadius: 2 }}>
              <div
                style={{
                  width: `${ratio * 100}%`,
                  height: '100%',
                  background: 'var(--accent)',
                  borderRadius: 2,
                }}
              />
            </span>
            <span className="right mono muted" style={{ fontSize: 11 }}>{row.count}</span>
          </div>
        )
      })}
    </div>
  )
}
