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

interface Props {
  brightness: number
  contrast: number
  saturation: number
  onChange: (key: 'brightness' | 'contrast' | 'saturation', value: number) => void
  onReset: () => void
}

/**
 * Picture-tuning menu with three sliders. Values are 0.5..1.5 (50%..150%).
 * Applied via CSS `filter` on the underlying <video> element (handled by
 * the parent so libass canvas overlay isn't tinted along with it).
 */
export default function PictureMenu({
  brightness,
  contrast,
  saturation,
  onChange,
  onReset,
}: 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 isModified =
    Math.abs(brightness - 1) > 0.001 ||
    Math.abs(contrast - 1) > 0.001 ||
    Math.abs(saturation - 1) > 0.001

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(o => !o)}
        className={`w-9 h-9 rounded-full grid place-items-center transition-colors focus-ring ${
          isModified
            ? 'text-accent bg-accent/15'
            : open
              ? 'bg-white/15 text-white'
              : 'text-white/85 hover:text-white hover:bg-white/10'
        }`}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-label="Picture"
        title="Picture"
      >
        <Palette 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="dialog"
            className="absolute right-0 top-full mt-2 w-[280px] 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 flex items-center justify-between">
              <p className="text-[10px] uppercase tracking-[0.14em] font-semibold text-white/60">
                Picture
              </p>
              {isModified && (
                <button
                  onClick={onReset}
                  className="inline-flex items-center gap-1 text-[10.5px] text-white/65 hover:text-white transition-colors focus-ring rounded"
                >
                  <RotateCcw size={11} />
                  Reset
                </button>
              )}
            </div>
            <div className="p-4 space-y-4">
              <Slider label="Brightness" value={brightness} onChange={v => onChange('brightness', v)} />
              <Slider label="Contrast" value={contrast} onChange={v => onChange('contrast', v)} />
              <Slider label="Saturation" value={saturation} onChange={v => onChange('saturation', v)} />
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

function Slider({
  label,
  value,
  onChange,
}: {
  label: string
  value: number
  onChange: (v: number) => void
}) {
  return (
    <div>
      <div className="flex items-baseline justify-between mb-1.5">
        <span className="text-[11.5px] font-medium text-white/80">{label}</span>
        <span className="text-[11px] font-mono tabular-nums text-white/55">
          {Math.round(value * 100)}%
        </span>
      </div>
      <input
        type="range"
        min={0.5}
        max={1.5}
        step={0.01}
        value={value}
        onChange={e => onChange(Number(e.target.value))}
        onDoubleClick={() => onChange(1)}
        className="slider w-full"
        aria-label={label}
      />
    </div>
  )
}
