import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Play, X } from '../../lib/icons'
import { getImageUrl } from '../../api/jellyfin'
import { jellyfinClient } from '../../api/jellyfin'
import type { BaseItemDto } from '../../api/types'

interface Props {
  open: boolean
  previousEpisodes: BaseItemDto[]
  daysSinceLastWatch: number | null
  onDismiss: () => void
}

const AUTO_DISMISS_SEC = 12

/**
 * "Previously on..." card shown before playback starts when the user is
 * returning to a series after a long break. Surfaces stills + summaries
 * of the 1-2 prior episodes so they re-enter the story without rewatching.
 *
 * Auto-dismisses after 12 seconds; clicking anywhere outside the cards
 * (or the X) dismisses early.
 */
export default function RecapCard({ open, previousEpisodes, daysSinceLastWatch, onDismiss }: Props) {
  const [countdown, setCountdown] = useState(AUTO_DISMISS_SEC)

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

  const auth = jellyfinClient.getAuthState()
  const serverUrl = auth?.serverUrl || ''

  const gapLabel = (() => {
    if (daysSinceLastWatch == null) return null
    if (daysSinceLastWatch < 30) return `${Math.round(daysSinceLastWatch)} days`
    const months = Math.round(daysSinceLastWatch / 30)
    if (months < 12) return `${months} ${months === 1 ? 'month' : 'months'}`
    const years = Math.round(daysSinceLastWatch / 365 * 10) / 10
    return `${years} ${years === 1 ? 'year' : 'years'}`
  })()

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.22 }}
          onClick={onDismiss}
          className="absolute inset-0 z-30 grid place-items-center bg-black/65 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] }}
            onClick={e => e.stopPropagation()}
            className="bg-glass-strong backdrop-blur-2xl border border-white/14 rounded-2xl p-7 w-[min(720px,92vw)] shadow-[0_30px_80px_-20px_rgba(0,0,0,0.85)] relative"
          >
            <button
              onClick={onDismiss}
              aria-label="Dismiss recap"
              className="absolute top-3 right-3 w-8 h-8 grid place-items-center rounded-full text-white/60 hover:text-white hover:bg-white/10 transition focus-ring"
            >
              <X size={14} stroke={2} />
            </button>
            <p className="text-[11px] uppercase tracking-[0.18em] font-semibold text-white/60 mb-1">
              Previously on
            </p>
            {gapLabel && (
              <p className="text-[12px] text-white/45 mb-5 tracking-tight">
                It has been {gapLabel} since you last watched
              </p>
            )}

            <div className={`grid gap-3 mb-6 ${previousEpisodes.length > 1 ? 'sm:grid-cols-2' : ''}`}>
              {previousEpisodes.map(ep => {
                const tag = ep.ImageTags?.Primary
                const thumb = tag
                  ? getImageUrl(serverUrl, ep.Id!, 'Primary', 480, tag)
                  : null
                const sLabel = ep.ParentIndexNumber != null && ep.IndexNumber != null
                  ? `S${ep.ParentIndexNumber} · E${ep.IndexNumber}`
                  : ''
                return (
                  <div key={ep.Id} className="rounded-xl overflow-hidden bg-black/30 ring-1 ring-white/10">
                    {thumb && (
                      <div className="aspect-video bg-black/40 overflow-hidden">
                        <img src={thumb} alt={ep.Name || ''} className="w-full h-full object-cover" />
                      </div>
                    )}
                    <div className="p-3.5">
                      {sLabel && (
                        <p className="text-[10px] uppercase tracking-[0.14em] font-semibold text-accent/90 mb-1">
                          {sLabel}
                        </p>
                      )}
                      <p className="text-[13.5px] font-semibold text-white/95 mb-1.5 leading-tight tracking-tight">
                        {ep.Name}
                      </p>
                      {ep.Overview && (
                        <p className="text-[11.5px] text-white/65 leading-relaxed line-clamp-3">
                          {ep.Overview}
                        </p>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>

            <div className="flex items-center justify-center gap-2.5 flex-wrap">
              <button
                onClick={onDismiss}
                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" />
                Got it
                <span className="text-void/65 tabular-nums text-[11.5px]">({countdown}s)</span>
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
