import { cn, PEC_STATE_LABELS, PEC_TYPE_LABELS } from '@/lib/utils'
import type { PecMsgType, PecState } from '@/types/api.types'

interface PecBadgeProps {
  state?: PecState
  type?: PecMsgType
  className?: string
}

const STATE_COLORS: Record<PecState, string> = {
  draft: 'bg-gray-100 text-gray-700 border-gray-300',
  queued: 'bg-yellow-100 text-yellow-800 border-yellow-300',
  sent: 'bg-blue-100 text-blue-800 border-blue-300',
  accepted: 'bg-cyan-100 text-cyan-800 border-cyan-300',
  delivered: 'bg-green-100 text-green-800 border-green-300',
  received: 'bg-green-100 text-green-800 border-green-300',
  anomaly: 'bg-orange-100 text-orange-800 border-orange-300',
  failed: 'bg-red-100 text-red-800 border-red-300',
}

const STATE_ICONS: Record<PecState, string> = {
  draft: '',
  queued: '',
  sent: '',
  accepted: '',
  delivered: '',
  received: '',
  anomaly: '',
  failed: '',
}

const TYPE_COLORS: Record<string, string> = {
  posta_certificata: 'bg-blue-50 text-blue-700 border-blue-200',
  accettazione: 'bg-cyan-50 text-cyan-700 border-cyan-200',
  non_accettazione: 'bg-orange-50 text-orange-700 border-orange-200',
  avvenuta_consegna: 'bg-green-50 text-green-700 border-green-200',
  mancata_consegna: 'bg-red-50 text-red-700 border-red-200',
  errore_consegna: 'bg-red-50 text-red-700 border-red-200',
  presa_in_carico: 'bg-purple-50 text-purple-700 border-purple-200',
  preavviso_mancata_consegna: 'bg-amber-50 text-amber-700 border-amber-200',
  rilevazione_virus: 'bg-red-50 text-red-700 border-red-200',
  unknown: 'bg-gray-50 text-gray-700 border-gray-200',
}

/**
 * Badge che mostra lo stato di una PEC con colore e icona.
 */
export function PecStateBadge({ state, className }: { state: PecState; className?: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium',
        STATE_COLORS[state] || 'bg-gray-100 text-gray-700 border-gray-300',
        className,
      )}
    >
      <span>{STATE_ICONS[state] || '?'}</span>
      {PEC_STATE_LABELS[state] || state}
    </span>
  )
}

/**
 * Badge che mostra il tipo di messaggio PEC.
 */
export function PecTypeBadge({ type, className }: { type: PecMsgType; className?: string }) {
  return (
    <span
      className={cn(
        'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
        TYPE_COLORS[type] || 'bg-gray-50 text-gray-700 border-gray-200',
        className,
      )}
    >
      {PEC_TYPE_LABELS[type] || type}
    </span>
  )
}

export function PecBadge({ state, type, className }: PecBadgeProps) {
  if (state) return <PecStateBadge state={state} className={className} />
  if (type) return <PecTypeBadge type={type} className={className} />
  return null
}
