import type React from 'react'

interface HorizontalBarsRow {
  label: string
  count: number
}

interface HorizontalBarsProps<R extends HorizontalBarsRow = HorizontalBarsRow> {
  rows: R[]
  max: number
  onActivate?: (row: R) => void
}

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

  return (
    <div>
      {rows.map((row, i) => {
        const ratio = row.count / safeMax
        const activatable = onActivate != null
        const labelStyle: React.CSSProperties = {
          fontSize: 11,
          ...(activatable
            ? { color: 'var(--accent-ink)', cursor: 'pointer' }
            : {}),
        }
        const label = (
          <span
            className="mono truncate"
            style={labelStyle}
            onClick={activatable ? () => onActivate(row) : undefined}
            role={activatable ? 'button' : undefined}
            tabIndex={activatable ? 0 : undefined}
            onKeyDown={activatable ? (e) => { if (e.key === 'Enter') onActivate(row) } : undefined}
          >
            {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>
  )
}
