import type { KeyboardEvent } from 'react'
import { Box, Typography } from '@mui/material'
import { Tooltip } from '../../../components'
import { styles } from '../style'

export interface CategoryRowOtherProps {
  hiddenCount: number
  /** Label for the overflow row. Defaults to `'Others'`. */
  otherLabel?: string
  /** Count text with `{count}` placeholder. Defaults to `'{count}'`. */
  otherCountLabel?: string
  /**
   * When provided, the row becomes a button: clicking it (or Enter/Space)
   * fires `onShowAll`, expanding the widget to reveal every category. When
   * omitted the row renders as a static, non-interactive summary.
   */
  onShowAll?: () => void
  /** Tooltip shown over the button form. Defaults to `'Show all'`. */
  showAllLabel?: string
}

/**
 * Overflow summary row rendered after the last visible category row when
 * `data.length > maxItems`. Shows `Others <count>` (count muted, no
 * parentheses).
 *
 * When `onShowAll` is supplied the row is an interactive button — clicking
 * it (or Enter/Space) expands the widget to show all categories, mirroring
 * the Searcher's full-list view. Without `onShowAll` it stays a static,
 * non-interactive summary (backward-compatible default).
 */
export function CategoryRowOther({
  hiddenCount,
  otherLabel = 'Others',
  otherCountLabel = '{count}',
  onShowAll,
  showAllLabel = 'Show all',
}: CategoryRowOtherProps) {
  const countText = otherCountLabel.replace('{count}', String(hiddenCount))

  const count = (
    <Typography variant='body2' sx={styles.otherCount}>
      {countText}
    </Typography>
  )

  if (!onShowAll) {
    return (
      <Box sx={styles.otherRow}>
        <Typography variant='body2' sx={styles.otherLabel}>
          {otherLabel}
        </Typography>
        {count}
      </Box>
    )
  }

  const handleKey = (e: KeyboardEvent<HTMLSpanElement>): void => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault()
      onShowAll()
    }
  }

  // Only the label is the click target; the count stays static beside it.
  return (
    <Box sx={styles.otherRow}>
      <Tooltip title={showAllLabel}>
        <Typography
          variant='body2'
          component='span'
          role='button'
          tabIndex={0}
          onClick={onShowAll}
          onKeyDown={handleKey}
          sx={{ ...styles.otherLabel, ...styles.otherLabelButton }}
        >
          {otherLabel}
        </Typography>
      </Tooltip>
      {count}
    </Box>
  )
}
