import styles from './Badge.module.css'
import { hashColor } from '../../utils/hashColor'
import { useTheme } from '../../providers/ThemeProvider'

type BadgeColor = 'primary' | 'success' | 'warning' | 'error' | 'running' | 'auto'
type BadgeVariant = 'filled' | 'outlined' | 'dashed'

interface BadgeProps {
  label: string
  variant?: BadgeVariant
  color?: BadgeColor
  onRemove?: () => void
  className?: string
}

export function Badge({
  label,
  variant = 'filled',
  color = 'auto',
  onRemove,
  className,
}: BadgeProps) {
  const { theme } = useTheme()
  const isAuto = color === 'auto'
  const hashColors = isAuto ? hashColor(label, theme) : null

  const inlineStyle = isAuto
    ? {
        backgroundColor: variant === 'filled' ? hashColors!.bg : 'transparent',
        color: hashColors!.text,
        borderColor: hashColors!.border,
      }
    : undefined

  const classes = [
    styles.badge,
    styles[variant],
    !isAuto ? styles[color] : '',
    className ?? '',
  ].filter(Boolean).join(' ')

  return (
    <span className={classes} style={inlineStyle}>
      {label}
      {onRemove && (
        <button className={styles.remove} onClick={onRemove} aria-label={`Remove ${label}`}>
          &times;
        </button>
      )}
    </span>
  )
}
