import { Box, Typography } from '@mui/material'
import { styles } from './styles'
import {
  LegendSwatch,
  DEFAULT_SWATCH_SIZE,
} from '../legend-swatch/legend-swatch'
import type { LegendCategoryVariable } from '../../stores'

export interface LegendCategoryUIProps {
  data: LegendCategoryVariable
}

const MIN_GUTTER = 16

/**
 * Categorical legend — a list of swatches with labels (and optional trailing
 * values, compact-formatted). The variable-level shape / fill pattern /
 * stroke style / `isStrokeColor` act as defaults; each item may override any
 * of them, so one list can mix patterns (or shapes) across entries.
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendCategoryUI({ data }: LegendCategoryUIProps) {
  const {
    items,
    shape = 'circle',
    isStrokeColor = false,
    fillPattern = 'solid',
    strokeStyle = 'solid',
    orientation = 'vertical',
  } = data
  const horizontal = orientation === 'horizontal'

  // Fixed gutter wide enough for the largest swatch so labels align — only
  // meaningful in the vertical list; horizontal chips size to content.
  const maxSize = items.reduce(
    (m, it) => Math.max(m, it.size ?? DEFAULT_SWATCH_SIZE),
    0,
  )
  const gutter = Math.max(MIN_GUTTER, maxSize)

  return (
    <Box
      data-orientation={orientation}
      sx={{ ...styles.list, ...(horizontal ? styles.listHorizontal : null) }}
    >
      {items.map((item, index) => (
        <Box
          key={`${item.label}-${index}`}
          sx={{
            ...styles.item,
            ...(horizontal ? styles.itemHorizontal : null),
          }}
        >
          <Box
            sx={{ ...styles.gutter, width: horizontal ? undefined : gutter }}
          >
            <LegendSwatch
              shape={item.shape ?? shape}
              color={item.color}
              isStrokeColor={item.isStrokeColor ?? isStrokeColor}
              fillPattern={item.fillPattern ?? fillPattern}
              strokeStyle={item.strokeStyle ?? strokeStyle}
              size={item.size ?? DEFAULT_SWATCH_SIZE}
            />
          </Box>
          <Typography
            variant='caption'
            color='text.primary'
            sx={{
              ...styles.label,
              ...(horizontal ? styles.labelHorizontal : null),
            }}
          >
            {item.label}
          </Typography>
          {item.value != null && (
            <Typography
              className='PsLegend-value'
              variant='caption'
              color='text.secondary'
              sx={styles.value}
            >
              {item.value}
            </Typography>
          )}
        </Box>
      ))}
    </Box>
  )
}
