import type { KeyboardEvent } from 'react'
import { Box, Typography } from '@mui/material'
import { CategoryBar } from './category-bar'
import type { CategoryKey, CategorySize } from '../types'
import { styles } from '../style'

export interface CategoryRowMultiProps {
  /** Raw category key — what gets emitted to `onToggle`. */
  name: CategoryKey
  /** Display label (post-`labelFormatter`). Falls back to `name`. */
  displayName?: string | number
  /** One value per series. `0` is rendered as an empty bar (track only). */
  values: readonly number[]
  /** One color per series (palette + per-series overrides resolved upstream). */
  colors: readonly string[]
  /** Shared max across all series + rows (or `maxOverride`). */
  maxValue: number
  formatter: (n: number) => string
  selected: boolean
  onToggle: (name: CategoryKey) => void
  /** Bar visual density. Forwarded to every {@link CategoryBar} in the row. */
  size?: CategorySize
}

/**
 * Multi-series category row: label spans the top; bar+value pairs stack
 * vertically below, one per series. Each bar uses the full row width
 * track (no shared grid) for legibility at N>=2 series. Click anywhere
 * in the row (label OR any bar/value) toggles selection by `name`.
 *
 * Visual selection / dim signal lives ENTIRELY in the bar colors
 * (`colors` prop) — every series in a dimmed row receives
 * `theme.palette.action.disabled`; selected / unselected-no-selection
 * rows receive their real palette colors. Computed upstream by
 * `CategoryUI`. The row itself has no bg tint, no opacity rule.
 */
export function CategoryRowMulti({
  name,
  displayName,
  values,
  colors,
  maxValue,
  formatter,
  selected,
  onToggle,
  size,
}: CategoryRowMultiProps) {
  const handleKey = (e: KeyboardEvent<HTMLDivElement>): void => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault()
      onToggle(name)
    }
  }
  return (
    <Box
      role='button'
      aria-pressed={selected}
      tabIndex={0}
      onClick={() => onToggle(name)}
      onKeyDown={handleKey}
      sx={styles.rowMulti}
    >
      <Typography variant='body2' sx={styles.multiName}>
        {displayName ?? name}
      </Typography>
      {values.map((v, i) => (
        // Multi-bar rows iterate per series — the bar belongs to series `i`,
        // and the row is keyed on the parent's `name`, so a composite of
        // `name` + the series index is stable across reorders.
        <Box key={`${name}-series-${i}`} sx={styles.multiBarRow}>
          <Box sx={styles.multiBarContainer}>
            <CategoryBar
              value={v}
              maxValue={maxValue}
              color={colors[i] ?? ''}
              size={size}
            />
          </Box>
          <Typography variant='body2' sx={styles.value}>
            {formatter(v)}
          </Typography>
        </Box>
      ))}
    </Box>
  )
}
