import { useEffect, useRef, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Adjustments, Check } from '../../lib/icons'

export interface QualityOption {
  /** Stable key for the menu */
  key: string
  /** Bitrate cap in bps to send as MaxStreamingBitrate. 0 = "unlimited" (Original). */
  bitrate: number
  label: string
  /** Optional sub-text shown smaller next to the label */
  hint?: string
}

const QUALITIES: QualityOption[] = [
  { key: 'auto', bitrate: 120_000_000, label: 'Auto', hint: 'Best for connection' },
  { key: 'original', bitrate: 0, label: 'Original', hint: 'Direct stream' },
  { key: '4k', bitrate: 20_000_000, label: '4K', hint: '20 Mbps' },
  { key: '1080', bitrate: 10_000_000, label: '1080p', hint: '10 Mbps' },
  { key: '720', bitrate: 4_000_000, label: '720p', hint: '4 Mbps' },
  { key: '480', bitrate: 2_000_000, label: '480p', hint: '2 Mbps' },
  { key: '360', bitrate: 800_000, label: '360p', hint: '800 Kbps' },
]

interface Props {
  selectedKey: string
  onSelect: (q: QualityOption) => void
}

export default function QualityMenu({ selectedKey, onSelect }: Props) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function onDoc(e: MouseEvent) {
      if (!ref.current) return
      if (!ref.current.contains(e.target as Node)) setOpen(false)
    }
    if (open) {
      window.addEventListener('mousedown', onDoc)
      return () => window.removeEventListener('mousedown', onDoc)
    }
  }, [open])

  const selected = QUALITIES.find(q => q.key === selectedKey) || QUALITIES[0]

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(o => !o)}
        className={`w-9 h-9 rounded-full grid place-items-center text-white/85 hover:text-white hover:bg-white/10 transition-colors focus-ring ${
          open ? 'bg-white/15 text-white' : ''
        }`}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`Quality: ${selected.label}`}
        title={`Quality: ${selected.label}`}
      >
        <Adjustments size={17} />
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -4, scale: 0.96 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -4, scale: 0.96 }}
            transition={{ duration: 0.15, ease: [0.16, 1, 0.3, 1] }}
            role="listbox"
            className="absolute right-0 top-full mt-2 w-56 bg-black/85 backdrop-blur-xl border border-white/12 rounded-lg shadow-2xl"
          >
            <div className="sticky top-0 px-3 py-2.5 bg-black/90 border-b border-white/8 z-10">
              <p className="text-[10px] uppercase tracking-[0.14em] font-semibold text-white/60">
                Quality
              </p>
            </div>
            <div className="p-1">
              {QUALITIES.map(q => {
                const sel = q.key === selectedKey
                return (
                  <button
                    key={q.key}
                    onClick={() => {
                      onSelect(q)
                      setOpen(false)
                    }}
                    role="option"
                    aria-selected={sel}
                    className={`w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-left transition-colors duration-100 focus-ring ${
                      sel ? 'bg-accent/15' : 'hover:bg-white/8'
                    }`}
                  >
                    <span
                      className={`w-4 h-4 grid place-items-center shrink-0 ${
                        sel ? 'text-accent' : 'text-transparent'
                      }`}
                    >
                      <Check size={13} strokeWidth={2.5} />
                    </span>
                    <span className="flex-1 min-w-0">
                      <span
                        className={`block text-[12.5px] font-medium ${
                          sel ? 'text-accent' : 'text-white'
                        }`}
                      >
                        {q.label}
                      </span>
                      {q.hint && (
                        <span className="block text-[10.5px] text-white/55 truncate">{q.hint}</span>
                      )}
                    </span>
                  </button>
                )
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

export { QUALITIES }
