import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Play, RotateCcw } from '../../lib/icons'
import { formatRuntime } from '../../lib/format'

interface Props {
  open: boolean
  positionTicks: number
  /** ISO timestamp of the last play, if known. Renders "Last watched X
   *  ago" under the main message so the user remembers when they were
   *  on this item - useful when picking up after a long break or coming
   *  back from another device. */
  lastPlayedDate?: string | null
  onResume: () => void
  onRestart: () => void
}

function formatRelativeAgo(iso: string): string {
  const then = Date.parse(iso)
  if (!Number.isFinite(then)) return ''
  const ms = Date.now() - then
  if (ms < 0) return ''
  const minutes = Math.floor(ms / 60_000)
  if (minutes < 1) return 'just now'
  if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`
  const days = Math.floor(hours / 24)
  if (days < 7) return `${days} day${days === 1 ? '' : 's'} ago`
  const weeks = Math.floor(days / 7)
  if (weeks < 5) return `${weeks} week${weeks === 1 ? '' : 's'} ago`
  const months = Math.floor(days / 30)
  if (months < 12) return `${months} month${months === 1 ? '' : 's'} ago`
  const years = Math.floor(days / 365)
  return `${years} year${years === 1 ? '' : 's'} ago`
}

const AUTO_CONFIRM_SEC = 6

/**
 * Lightweight overlay shown on player entry when a resume position exists
 * and the user has the "ask before resuming" pref on. Two buttons -
 * Resume from M:SS / Start over - with a 6-second auto-confirm on Resume
 * so it doesn't feel like a wall.
 */
export default function ResumePrompt({ open, positionTicks, lastPlayedDate, onResume, onRestart }: Props) {
  const [countdown, setCountdown] = useState(AUTO_CONFIRM_SEC)
  const ago = lastPlayedDate ? formatRelativeAgo(lastPlayedDate) : ''

  useEffect(() => {
    if (!open) return
    setCountdown(AUTO_CONFIRM_SEC)
    const id = setInterval(() => {
      setCountdown(c => {
        if (c <= 1) {
          clearInterval(id)
          onResume()
          return 0
        }
        return c - 1
      })
    }, 1000)
    return () => clearInterval(id)
  }, [open, onResume])

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.22 }}
          className="absolute inset-0 z-30 grid place-items-center bg-black/55 backdrop-blur-sm"
        >
          <motion.div
            initial={{ y: 24, scale: 0.96 }}
            animate={{ y: 0, scale: 1 }}
            exit={{ y: 24, scale: 0.96 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            className="bg-glass-strong backdrop-blur-2xl border border-white/14 rounded-2xl p-7 max-w-md text-center shadow-[0_30px_80px_-20px_rgba(0,0,0,0.85)]"
          >
            <p className="text-[11px] uppercase tracking-[0.18em] font-semibold text-white/60 mb-2">
              Continue watching
            </p>
            <p className="text-[16px] text-white/90 mb-1 tracking-tight">
              You left off at <span className="font-display font-bold text-accent tabular-nums">{formatRuntime(positionTicks)}</span>
            </p>
            {ago && (
              <p className="text-[11.5px] text-white/55 mb-6 tracking-tight">
                Last watched {ago}
              </p>
            )}
            {!ago && <div className="mb-6" />}
            <div className="flex items-center gap-2.5 justify-center flex-wrap">
              <button
                onClick={onResume}
                autoFocus
                className="inline-flex items-center gap-2 h-11 px-5 rounded-full bg-accent hover:bg-accent-hover text-void text-[13px] font-semibold tracking-tight transition-[transform,background] duration-200 ease-out hover:scale-[1.03] active:scale-[0.97] focus-ring shadow-[0_8px_24px_-8px_rgba(245,182,66,0.5)]"
              >
                <Play size={14} fill="currentColor" />
                Resume
                <span className="text-void/65 tabular-nums text-[11.5px]">({countdown}s)</span>
              </button>
              <button
                onClick={onRestart}
                className="inline-flex items-center gap-2 h-11 px-5 rounded-full bg-white/8 hover:bg-white/14 backdrop-blur text-white text-[13px] font-medium tracking-tight border border-white/14 hover:border-white/25 transition-all duration-200 ease-out active:scale-[0.97] focus-ring"
              >
                <RotateCcw size={14} stroke={2} />
                Start over
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
