import { motion } from 'framer-motion'
import { HardDrive } from '../../lib/icons'
import type { BaseItemDto } from '../../api/types'
import { summarizeSource } from '../../lib/jellyfin-meta'

interface Props {
  item: BaseItemDto
  selectedSourceId: string | null
  onChange: (sourceId: string) => void
}

export default function VersionsSelector({ item, selectedSourceId, onChange }: Props) {
  const sources = item.MediaSources || []
  if (sources.length <= 1) return null

  return (
    <div className="space-y-2">
      <p className="text-[10px] font-semibold text-white/55 uppercase tracking-[0.14em] flex items-center gap-1.5">
        <HardDrive size={10} />
        Available versions
      </p>
      <div className="flex gap-2 flex-wrap">
        {sources.map(src => {
          const summary = summarizeSource(src)
          const id = src.Id || ''
          const active = id === selectedSourceId
          return (
            <button
              key={id}
              onClick={() => onChange(id)}
              className={`relative h-auto min-h-9 px-3 py-1.5 text-left rounded-md border transition-all duration-150 focus-ring ${
                active
                  ? 'bg-accent/15 border-accent/40 text-accent'
                  : 'bg-white/5 border-white/10 text-white/80 hover:bg-white/10 hover:border-white/20'
              }`}
            >
              {active && (
                <motion.span
                  layoutId="version-active"
                  className="absolute inset-0 rounded-md ring-1 ring-accent/50"
                  transition={{ type: 'spring', stiffness: 380, damping: 30 }}
                />
              )}
              <span className="relative block text-[12px] font-semibold tracking-tight">
                {summary.label || src.Name || 'Version'}
              </span>
              {summary.detail && (
                <span className="relative block text-[10px] text-white/55 mt-0.5">{summary.detail}</span>
              )}
            </button>
          )
        })}
      </div>
    </div>
  )
}
