import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  ChevronDown,
  Film,
  Activity,
  Bolt,
  HardDrive,
  Boxes,
  Volume2,
  Subtitles,
  CalendarPlus,
} from '../../lib/icons'
import type { BaseItemDto } from '../../api/types'
import {
  pickPrimarySource,
  getVideoStream,
  getAudioStreams,
  getSubtitleStreams,
  resolutionLabel,
  videoCodecLabel,
  framerateLabel,
  videoRangeLabel,
  audioFormatLabel,
  subtitleLabel,
} from '../../lib/jellyfin-meta'
import { formatBitrate, formatBytes, formatDate, languageLabel } from '../../lib/format'
import StatTile, { type StatTileData } from '../ui/StatTile'
import MediaTechIcons from '../ui/MediaTechIcons'

interface Props {
  item: BaseItemDto
}

export function hasTechSpecs(item: BaseItemDto): boolean {
  const source = pickPrimarySource(item)
  const video = getVideoStream(item)
  return !!(source || video)
}

export default function TechSpecs({ item }: Props) {
  const source = pickPrimarySource(item)
  const video = getVideoStream(item)
  const audio = getAudioStreams(item)
  const subs = getSubtitleStreams(item)
  const [open, setOpen] = useState(false)

  if (!source && !video) return null

  const tiles: StatTileData[] = []
  const res = resolutionLabel(item)
  const range = videoRangeLabel(item)
  if (res) {
    tiles.push({
      icon: Film,
      label: 'Resolution',
      value: range ? `${res} · ${range}` : res,
      tone: range ? 'amber' : 'default',
    })
  }
  if (video) {
    const codec = videoCodecLabel(video)
    if (codec) tiles.push({ icon: Film, label: 'Codec', value: codec })
    const fps = framerateLabel(video)
    if (fps) tiles.push({ icon: Activity, label: 'Frame rate', value: fps })
    if (video.BitRate) {
      tiles.push({
        icon: Bolt,
        label: 'Video bitrate',
        value: formatBitrate(video.BitRate),
      })
    }
  }
  if (audio[0]) {
    const a = audioFormatLabel(audio[0])
    if (a) tiles.push({ icon: Volume2, label: 'Audio', value: a })
  }
  if (subs.length) {
    tiles.push({
      icon: Subtitles,
      label: 'Subtitles',
      value: `${subs.length} track${subs.length === 1 ? '' : 's'}`,
    })
  }
  if (source?.Container) {
    tiles.push({ icon: Boxes, label: 'Container', value: source.Container.toUpperCase() })
  }
  if (source?.Bitrate) {
    tiles.push({ icon: Bolt, label: 'Total bitrate', value: formatBitrate(source.Bitrate) })
  }
  if (source?.Size) {
    tiles.push({ icon: HardDrive, label: 'File size', value: formatBytes(source.Size) })
  }
  if (item.DateCreated) {
    tiles.push({
      icon: CalendarPlus,
      label: 'Added',
      value: formatDate(item.DateCreated),
      tone: 'amber',
    })
  }

  return (
    <div className="space-y-4">
      {/* Top: tech badge strip */}
      <MediaTechIcons item={item} />

      {/* Tile grid */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
        {tiles.map(t => (
          <StatTile key={t.label} tile={t} />
        ))}
      </div>

      {/* Per-stream details */}
      <div className="rounded-lg border border-border overflow-hidden">
        <button
          onClick={() => setOpen(o => !o)}
          className="w-full flex items-center justify-between px-4 py-2.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-text-3 hover:text-text-1 hover:bg-glass-light transition-colors focus-ring"
          aria-expanded={open}
        >
          <span className="flex items-center gap-2">
            <span className="w-1 h-3.5 rounded-full bg-accent/60" />
            Per-stream details
            <span className="text-text-4 lowercase tracking-normal font-normal text-[11px]">
              ({1 + audio.length + subs.length} stream{1 + audio.length + subs.length === 1 ? '' : 's'})
            </span>
          </span>
          <ChevronDown
            size={13}
            className={`transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
          />
        </button>

        <AnimatePresence initial={false}>
          {open && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
              className="overflow-hidden border-t border-border"
            >
              <div className="p-3 space-y-2">
                {video && (
                  <StreamRow
                    icon={Film}
                    type="Video"
                    primary={[
                      videoCodecLabel(video),
                      video.Width && video.Height ? `${video.Width}×${video.Height}` : '',
                      framerateLabel(video),
                    ].filter(Boolean).join(' · ')}
                    secondary={[
                      video.BitRate ? formatBitrate(video.BitRate) : '',
                      video.BitDepth ? `${video.BitDepth}-bit` : '',
                      video.PixelFormat,
                      video.ColorSpace?.toUpperCase(),
                    ].filter(Boolean).join(' · ')}
                    flags={[
                      range && { label: range, tone: 'amber' as const },
                    ].filter((x): x is { label: string; tone: 'amber' } => !!x)}
                  />
                )}
                {audio.map((a, i) => (
                  <StreamRow
                    key={`a-${i}`}
                    icon={Volume2}
                    type={`Audio ${audio.length > 1 ? i + 1 : ''}`.trim()}
                    primary={audioFormatLabel(a) || 'Unknown'}
                    secondary={[
                      languageLabel(a.Language),
                      a.BitRate ? formatBitrate(a.BitRate) : '',
                      a.SampleRate ? `${(a.SampleRate / 1000).toFixed(1)} kHz` : '',
                    ].filter(Boolean).join(' · ')}
                    flags={[
                      a.IsDefault && { label: 'Default', tone: 'accent' as const },
                    ].filter((x): x is { label: string; tone: 'accent' } => !!x)}
                  />
                ))}
                {subs.map((s, i) => {
                  const flags: { label: string; tone: 'cool' | 'accent' | 'success' | 'muted' }[] = []
                  if (s.IsDefault) flags.push({ label: 'Default', tone: 'accent' })
                  if (s.IsForced) flags.push({ label: 'Forced', tone: 'cool' })
                  if (s.IsHearingImpaired) flags.push({ label: 'SDH', tone: 'success' })
                  if (s.IsExternal) flags.push({ label: 'External', tone: 'muted' })
                  return (
                    <StreamRow
                      key={`s-${i}`}
                      icon={Subtitles}
                      type={`Subtitle ${subs.length > 1 ? i + 1 : ''}`.trim()}
                      primary={subtitleLabel(s).split(' (')[0] || 'Unknown'}
                      secondary={[
                        s.Codec?.toUpperCase(),
                        s.Title && s.Title !== s.DisplayTitle ? s.Title : '',
                      ].filter(Boolean).join(' · ')}
                      flags={flags}
                    />
                  )
                })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  )
}

function StreamRow({
  icon: Icon,
  type,
  primary,
  secondary,
  flags,
}: {
  icon: typeof Film
  type: string
  primary: string
  secondary?: string
  flags?: { label: string; tone: 'amber' | 'cool' | 'accent' | 'success' | 'muted' }[]
}) {
  return (
    <div className="flex items-start gap-3 p-3 rounded-md bg-elevated/30 border border-border/60">
      <span className="shrink-0 w-8 h-8 rounded-md grid place-items-center bg-glass-light text-text-2 ring-1 ring-border">
        <Icon size={14} stroke={1.75} />
      </span>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap mb-1">
          <span className="text-[10px] uppercase tracking-[0.14em] font-semibold text-text-3 leading-none">
            {type}
          </span>
          {flags?.map(f => (
            <Flag key={f.label} label={f.label} tone={f.tone} />
          ))}
        </div>
        <p className="text-[13px] text-text-1 font-semibold tracking-tight truncate">
          {primary}
        </p>
        {secondary && (
          <p className="text-[11.5px] text-text-3 mt-0.5 tabular-nums truncate font-mono">
            {secondary}
          </p>
        )}
      </div>
    </div>
  )
}

function Flag({
  label,
  tone,
}: {
  label: string
  tone: 'amber' | 'cool' | 'accent' | 'success' | 'muted'
}) {
  const cls =
    tone === 'amber' ? 'bg-amber-500/15 text-amber-200 ring-amber-500/25'
    : tone === 'cool' ? 'bg-cool/15 text-cool ring-cool/25'
    : tone === 'accent' ? 'bg-accent/15 text-accent ring-accent/25'
    : tone === 'success' ? 'bg-success/15 text-success ring-success/25'
    : 'bg-glass-light text-text-2 ring-border'
  return (
    <span className={`inline-flex items-center h-4 px-1.5 rounded text-[9px] font-bold uppercase tracking-wider ring-1 leading-none ${cls}`}>
      {label}
    </span>
  )
}
