import { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { EPISODE_GROUP_TYPES, type OrderingOption } from '../../lib/episode-order'
import type { TmdbEpisodeGroup } from '../../api/tmdb'

interface Props {
  groups: TmdbEpisodeGroup[]
  selectedId: string
  onChange: (id: string) => void
}

/**
 * Compact dropdown that lets users switch between aired order and any
 * alternative TMDB episode groups. Filters out tiny groups (<5
 * episodes) since those are usually fragments, not real orderings.
 */
export default function EpisodeOrderToggle({ groups, selectedId, onChange }: Props) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  const options: OrderingOption[] = [
    { id: 'aired', label: 'Aired order' },
    ...groups
      .filter(g => g.episode_count >= 5 && g.type !== 1)
      .map(g => ({
        id: g.id,
        label: g.name || EPISODE_GROUP_TYPES[g.type] || 'Alternate',
        description: EPISODE_GROUP_TYPES[g.type],
      })),
  ]

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

  const current = options.find(o => o.id === selectedId) || options[0]

  if (options.length <= 1) return null

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen(v => !v)}
        className="inline-flex items-center gap-1.5 h-7 px-2.5 rounded-lg bg-elevated/60 ring-1 ring-border hover:ring-border-strong text-[11.5px] text-text-2 hover:text-text-1 transition tracking-tight"
      >
        <svg className="w-3 h-3 opacity-70" viewBox="0 0 20 20" fill="currentColor">
          <path d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 5a1 1 0 011-1h8a1 1 0 110 2H4a1 1 0 01-1-1zm0 5a1 1 0 011-1h4a1 1 0 110 2H4a1 1 0 01-1-1z" />
        </svg>
        <span className="font-medium">{current.label}</span>
        <svg className={`w-3 h-3 opacity-60 transition ${open ? 'rotate-180' : ''}`} viewBox="0 0 20 20" fill="currentColor">
          <path d="M5.5 7.5L10 12l4.5-4.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.18, ease: [0.16, 1, 0.3, 1] }}
            className="absolute right-0 top-full mt-1.5 z-30 min-w-[180px] rounded-xl bg-surface/95 backdrop-blur-md ring-1 ring-border-strong shadow-xl overflow-hidden"
          >
            {options.map(opt => (
              <button
                key={opt.id}
                type="button"
                onClick={() => {
                  onChange(opt.id)
                  setOpen(false)
                }}
                className={`w-full text-left px-3 py-2 text-[12px] hover:bg-elevated/80 transition ${
                  opt.id === selectedId ? 'text-accent' : 'text-text-2'
                }`}
              >
                <div className="font-medium leading-tight">{opt.label}</div>
                {opt.description && opt.description !== opt.label && (
                  <div className="text-[10px] text-text-4 mt-0.5">{opt.description}</div>
                )}
              </button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
