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 CategoryRowSingleProps {
  /** Raw category key — what gets emitted to `onToggle` regardless of formatter. */
  name: CategoryKey
  /** Display label (post-`labelFormatter`). Falls back to `name` when omitted. */
  displayName?: string | number
  value: number
  maxValue: number
  color: string
  formatter: (n: number) => string
  selected: boolean
  onToggle: (name: CategoryKey) => void
  /** Bar visual density. Forwarded to {@link CategoryBar}. */
  size?: CategorySize
}

/**
 * Single-series category row: `[label] [bar] [value]` grid. Click /
 * Enter / Space toggles `name` in/out of the selection set via
 * `onToggle`. Selection key is always the raw `name` — `displayName` is
 * presentation only.
 *
 * Visual selection / dim signal lives ENTIRELY in the bar color
 * (`color` prop) — computed upstream by `CategoryUI` (real palette
 * color when selected or no-selection; `theme.palette.action.disabled`
 * when a selection exists and this row isn't in it). The row itself
 * has no bg tint, no opacity rule.
 */
export function CategoryRowSingle({
  name,
  displayName,
  value,
  maxValue,
  color,
  formatter,
  selected,
  onToggle,
  size,
}: CategoryRowSingleProps) {
  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.rowSingle}
    >
      <Box sx={styles.rowHeader}>
        <Typography variant='body2' sx={styles.name}>
          {displayName ?? name}
        </Typography>
        <Typography variant='body2' sx={styles.value}>
          {formatter(value)}
        </Typography>
      </Box>
      <CategoryBar
        value={value}
        maxValue={maxValue}
        color={color}
        size={size}
      />
    </Box>
  )
}
