import { tagColorVar, type Tag } from '../../api/client'

interface Props {
  tag: Tag
  // When set, renders an interactive chip (filter toggle); `active` fills it.
  onClick?: () => void
  active?: boolean
  // When set, shows a small × to remove the tag (used on document rows).
  onRemove?: () => void
  // Optional trailing count (used in the filter bar).
  count?: number
  size?: 'sm' | 'md'
}

// TagChip is the pill used everywhere a tag appears: on document rows, in the
// filter bar, and in the assign popover. The palette color tints a soft wash; a
// filled variant marks an active filter. Keeps tap targets comfortable on touch.
export function TagChip({ tag, onClick, active, onRemove, count, size = 'sm' }: Props) {
  const color = tagColorVar(tag.color)
  const interactive = !!onClick
  const pad = size === 'md' ? '0.3rem 0.7rem' : '0.12rem 0.5rem'
  const font = size === 'md' ? '0.8rem' : '0.7rem'

  return (
    <span
      onClick={
        onClick
          ? (e) => {
              e.stopPropagation()
              onClick()
            }
          : undefined
      }
      className={`petal-tag-chip inline-flex items-center gap-1 whitespace-nowrap font-bold${interactive ? ' cursor-pointer' : ''}`}
      style={{
        borderRadius: 'var(--radius-pill)',
        padding: pad,
        fontSize: font,
        lineHeight: 1.2,
        background: active ? color : 'color-mix(in srgb, ' + color + ' 22%, white)',
        color: active ? 'white' : 'var(--color-plum)',
        border: `1px solid ${active ? color : 'color-mix(in srgb, ' + color + ' 45%, white)'}`,
      }}
    >
      <span
        aria-hidden
        className="inline-block shrink-0"
        style={{
          width: 7,
          height: 7,
          borderRadius: 'var(--radius-pill)',
          background: active ? 'white' : color,
        }}
      />
      {tag.name}
      {typeof count === 'number' && (
        <span style={{ opacity: 0.7, fontWeight: 700 }}>{count}</span>
      )}
      {onRemove && (
        <button
          type="button"
          aria-label={`Remove ${tag.name}`}
          onClick={(e) => {
            e.stopPropagation()
            onRemove()
          }}
          className="ml-0.5 inline-flex items-center justify-center"
          style={{ color: 'inherit', opacity: 0.65, fontSize: '0.85em', lineHeight: 1 }}
        >
          ×
        </button>
      )}
    </span>
  )
}
