import { Box, Button, Typography, type SvgIconProps } from '@mui/material'
import type { ComponentType } from 'react'
import {
  DEFAULT_SELECTION_SUMMARY_LABELS,
  type SelectionSummaryLabels,
} from './labels'
import { styles } from './style'

export interface SelectionSummaryProps {
  /** Number of currently selected items. */
  count: number
  /** Optional total — when `undefined` or `0` the component renders nothing (no data). */
  total?: number
  /** Clear callback. The Clear control is shown only when `count > 0` and `onClear` is provided. */
  onClear?: () => void
  labels?: Partial<SelectionSummaryLabels>
  icon?: ComponentType<SvgIconProps>
  iconProps?: SvgIconProps
}

/**
 * Renders a `selected / total` count.
 *
 * Render rules:
 *   - `!total` (undefined or 0) → render nothing (no data to summarize).
 *   - `count === 0` → display `total / total` (everything is implicitly in
 *     scope); no Clear button.
 *   - `count > 0` → display `count / total` + Clear (when `onClear` is given).
 *
 * The count is two-tone by default (selected number bold/`text.primary`,
 * ` / total` in `text.secondary`). Pass `labels.summary` to render a custom
 * node instead — it receives the already-resolved displayed number (which
 * equals `total` when nothing is selected).
 */
export function SelectionSummary({
  count,
  total,
  onClear,
  labels,
  icon: Icon,
  iconProps,
}: SelectionSummaryProps) {
  if (!total) return null
  const _labels = { ...DEFAULT_SELECTION_SUMMARY_LABELS, ...labels }
  const shown = count === 0 ? total : count

  return (
    <Box sx={styles.root}>
      {Icon ? <Icon fontSize='small' {...iconProps} /> : null}
      <Box
        component='span'
        sx={styles.count}
        aria-label={`${shown} / ${total}`}
      >
        {_labels.summary ? (
          _labels.summary(shown, total)
        ) : (
          <>
            <Typography component='span' variant='caption' sx={styles.selected}>
              {shown}
            </Typography>
            <Typography
              component='span'
              variant='caption'
              sx={styles.separator}
            >
              /
            </Typography>
            <Typography component='span' variant='caption' sx={styles.total}>
              {total}
            </Typography>
          </>
        )}
      </Box>
      {count > 0 && onClear && (
        <Button size='small' variant='text' onClick={onClear}>
          {_labels.clear}
        </Button>
      )}
    </Box>
  )
}
