import clsx from 'clsx'

function toneClasses(tone: 'neutral' | 'success' | 'warning' | 'info') {
  switch (tone) {
    case 'success':
      return 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200'
    case 'warning':
      return 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-200'
    case 'info':
      return 'border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-200'
    default:
      return 'border-gray-200 bg-gray-50 text-gray-700 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300'
  }
}

function normalizeBadgeLabel(value: unknown): string {
  if (typeof value === 'string') return value
  if (typeof value === 'number' || typeof value === 'bigint' || typeof value === 'boolean') return String(value)
  return 'unknown'
}

export function getEntityBadgeTone(tag: unknown): 'neutral' | 'success' | 'warning' | 'info' {
  const normalized = normalizeBadgeLabel(tag).toLowerCase()
  if (normalized === 'compliant' || normalized === 'listed' || normalized === 'verified' || normalized === 'gru') {
    return 'success'
  }
  if (normalized === 'wrapped' || normalized === 'treasury-bond') {
    return 'warning'
  }
  if (normalized === 'bridge' || normalized === 'canonical' || normalized === 'official' || normalized === 'electronic-money' || normalized === 'commodity') {
    return 'info'
  }
  return 'neutral'
}

export function formatEntityBadgeLabel(label: unknown): string {
  const resolvedLabel = normalizeBadgeLabel(label)
  const normalized = resolvedLabel.toLowerCase()
  const labels: Record<string, string> = {
    'reference-asset': 'reference asset',
    'electronic-money': 'cash e-money',
    'treasury-bond': 'treasury / gov bond',
    gru: 'GRU',
  }
  return labels[normalized] || resolvedLabel
}

export default function EntityBadge({
  label,
  tone,
  className,
}: {
  label: unknown
  tone?: 'neutral' | 'success' | 'warning' | 'info'
  className?: string
}) {
  const resolvedTone = tone || getEntityBadgeTone(label)

  return (
    <span
      className={clsx(
        'rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-wide',
        toneClasses(resolvedTone),
        className,
      )}
    >
      {formatEntityBadgeLabel(label)}
    </span>
  )
}
