import { Box, Chip, Typography } from '@mui/material'
import type { SxProps, Theme } from '@mui/material'

interface ChipOption {
  value: string
  label: string
  color?: string
}

interface PriorityChipGroupProps {
  label?: string
  options: ChipOption[]
  value: string[]
  onChange: (value: string[]) => void
  exclusive?: boolean
  sx?: SxProps<Theme>
}

export function PriorityChipGroup({ label, options, value, onChange, exclusive = false, sx }: PriorityChipGroupProps) {
  function toggle(optValue: string) {
    if (exclusive) {
      onChange(value.includes(optValue) ? [] : [optValue])
    } else {
      onChange(
        value.includes(optValue)
          ? value.filter(v => v !== optValue)
          : [...value, optValue],
      )
    }
  }

  return (
    <Box sx={sx}>
      {label && (
        <Typography sx={{ fontSize: '0.75rem', color: 'text.secondary', mb: 0.75, fontWeight: 500 }}>
          {label}
        </Typography>
      )}
      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
        {options.map(opt => {
          const selected = value.includes(opt.value)
          const accent = opt.color ?? '#1e3a5f'
          return (
            <Chip
              key={opt.value}
              label={opt.label}
              size="small"
              clickable
              onClick={() => toggle(opt.value)}
              sx={{
                fontSize: '0.75rem',
                bgcolor: selected ? accent : 'transparent',
                color: selected ? '#fff' : 'text.secondary',
                border: '1px solid',
                borderColor: selected ? accent : 'divider',
                '&:hover': { bgcolor: selected ? accent : 'rgba(0,0,0,0.04)' },
              }}
            />
          )
        })}
      </Box>
    </Box>
  )
}
