import { Check, Clock, RefreshCw, AlertCircle } from '../../lib/icons'
import { useItemAvailability } from '../../hooks/use-availability'

interface Props {
  tmdbId: string | number | null | undefined
  /** Compact icon-only mode for poster overlays. */
  variant?: 'pill' | 'icon'
}

const TONE: Record<string, { label: string; color: string }> = {
  available: { label: 'Available', color: 'bg-success/20 text-success ring-success/30' },
  partial: { label: 'Partial', color: 'bg-amber-500/20 text-amber-200 ring-amber-400/30' },
  processing: { label: 'Downloading', color: 'bg-blue-500/20 text-blue-200 ring-blue-400/30' },
  pending: { label: 'Pending', color: 'bg-purple-500/20 text-purple-200 ring-purple-400/30' },
  requested: { label: 'Requested', color: 'bg-elevated/80 text-text-2 ring-border' },
}

/**
 * Renders a small status chip ("Available", "Downloading", "Pending"
 * etc.) sourced from `useItemAvailability`. Returns null when the item
 * isn't tracked anywhere - rendering "missing" as a chip would just be
 * noise on every card.
 */
export default function AvailabilityChip({ tmdbId, variant = 'pill' }: Props) {
  const record = useItemAvailability(tmdbId)
  if (!record || record.status === 'missing') return null
  const tone = TONE[record.status]
  if (!tone) return null

  if (variant === 'icon') {
    const Icon =
      record.status === 'available' ? Check
      : record.status === 'processing' ? RefreshCw
      : record.status === 'pending' ? Clock
      : AlertCircle
    return (
      <span
        className={`inline-flex items-center justify-center w-5 h-5 rounded-full ring-1 ${tone.color}`}
        title={tone.label}
      >
        <Icon size={10} stroke={2.25} />
      </span>
    )
  }

  return (
    <span
      className={`inline-flex items-center gap-1 h-[18px] px-1.5 rounded text-[9.5px] font-bold uppercase tracking-[0.06em] ring-1 backdrop-blur shadow-sm ${tone.color} ${
        record.status === 'processing' ? 'animate-pulse' : ''
      }`}
      title={tone.label}
    >
      {tone.label}
    </span>
  )
}
