/**
 * TagBadge – badge colorato per un singolo tag/label.
 *
 * Mostra il nome del tag con il colore di sfondo configurato.
 * Se `onRemove` è fornito, mostra un pulsante × per rimuovere il tag.
 */
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { LabelResponse } from '@/types/api.types'

// Colore di default quando il tag non ha colore configurato
const DEFAULT_COLOR = '#6b7280'

/**
 * Calcola il colore del testo (bianco o nero) in base alla luminosità
 * del colore di sfondo per garantire un contrasto leggibile.
 */
function getTextColor(hexColor: string): string {
  const hex = hexColor.replace('#', '')
  const r = parseInt(hex.substring(0, 2), 16)
  const g = parseInt(hex.substring(2, 4), 16)
  const b = parseInt(hex.substring(4, 6), 16)
  // Formula luminosità relativa (WCAG)
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
  return luminance > 0.5 ? '#1f2937' : '#ffffff'
}

interface TagBadgeProps {
  label: LabelResponse
  onRemove?: () => void
  size?: 'sm' | 'md'
  className?: string
}

export function TagBadge({ label, onRemove, size = 'sm', className }: TagBadgeProps) {
  const bgColor = label.color || DEFAULT_COLOR
  const textColor = getTextColor(bgColor)

  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 rounded-full font-medium transition-all',
        size === 'sm' ? 'px-2 py-0.5 text-xs' : 'px-2.5 py-1 text-sm',
        className,
      )}
      style={{ backgroundColor: bgColor, color: textColor }}
      title={label.name}
    >
      <span className="truncate max-w-[120px]">{label.name}</span>
      {onRemove && (
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation()
            onRemove()
          }}
          className="flex-shrink-0 rounded-full p-0.5 hover:opacity-70 transition-opacity"
          style={{ color: textColor }}
          aria-label={`Rimuovi tag ${label.name}`}
        >
          <X className="h-3 w-3" />
        </button>
      )}
    </span>
  )
}

/**
 * TagBadgeList – mostra una lista compatta di tag badge.
 * Se ci sono più tag del limite `maxVisible`, mostra un badge "+N".
 */
interface TagBadgeListProps {
  labels: LabelResponse[]
  onRemove?: (labelId: string) => void
  maxVisible?: number
  size?: 'sm' | 'md'
  className?: string
}

export function TagBadgeList({
  labels,
  onRemove,
  maxVisible = 3,
  size = 'sm',
  className,
}: TagBadgeListProps) {
  if (!labels || labels.length === 0) return null

  const visible = labels.slice(0, maxVisible)
  const overflow = labels.length - maxVisible

  return (
    <div className={cn('flex items-center gap-1 flex-wrap', className)}>
      {visible.map((label) => (
        <TagBadge
          key={label.id}
          label={label}
          onRemove={onRemove ? () => onRemove(label.id) : undefined}
          size={size}
        />
      ))}
      {overflow > 0 && (
        <span
          className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground"
          title={labels
            .slice(maxVisible)
            .map((l) => l.name)
            .join(', ')}
        >
          +{overflow}
        </span>
      )}
    </div>
  )
}
