import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { Play, Info, Star, Clock, X } from '../../lib/icons'
import { useQuickLookStore } from '../../stores/quick-look-store'
import { useItemDetails } from '../../hooks/use-jellyfin'
import { useTmdbMovie, useTmdbTvShow } from '../../hooks/use-tmdb'
import { getBestImage, getStoredServerUrl, getImageUrl } from '../../api/jellyfin'
import { getTmdbImageUrl, pickTmdbLogo } from '../../api/tmdb'
import { formatRuntime } from '../../lib/format'
import WatchlistButton from './WatchlistButton'
import RequestButton from '../request/RequestButton'
import { getTmdbId, asTmdbDetail } from '../../lib/item-types'

/**
 * Right-click / long-press peek for any item card. Renders a centered
 * modal with the backdrop, title, summary, top cast, and shortcut
 * actions (Play, More info). Doesn't navigate so the user keeps their
 * place in the browse view.
 */
export default function QuickLookModal() {
  const navigate = useNavigate()
  const target = useQuickLookStore(s => s.item)
  const close = useQuickLookStore(s => s.close)
  const open = !!target

  const { data: full } = useItemDetails(open && target?.Id && !String(target.Id).startsWith('tmdb-') ? target.Id : undefined)
  const item = full || target
  const tmdbId = getTmdbId(item)
  const numericTmdb = tmdbId ? Number(tmdbId) : null
  const isSeries = item?.Type === 'Series'
  const tmdbMovie = useTmdbMovie(!isSeries ? numericTmdb : null)
  const tmdbTv = useTmdbTvShow(isSeries ? numericTmdb : null)
  const tmdbData = asTmdbDetail(isSeries ? tmdbTv.data : tmdbMovie.data)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open, close])

  if (!open || !item) return null

  const serverUrl = getStoredServerUrl()
  const backdrop = serverUrl ? getBestImage(serverUrl, item, 'backdrop', 1280) : null
  const fallbackBackdrop = tmdbData?.backdrop_path ? getTmdbImageUrl(tmdbData.backdrop_path, 'w1280') : null
  const heroImg = backdrop || fallbackBackdrop

  const logoFromJf =
    item?.Id && item.ImageTags?.Logo
      ? getImageUrl(serverUrl, item.Id, 'Logo', 600, item.ImageTags.Logo)
      : null
  const logoFromTmdb = pickTmdbLogo(
    isSeries
      ? tmdbTv.data?.images?.logos
      : tmdbMovie.data?.images?.logos,
  )
  const logoUrl = logoFromJf || (logoFromTmdb ? getTmdbImageUrl(logoFromTmdb.file_path, 'w500') : null)

  const overview = item.Overview || tmdbData?.overview || ''
  const year = item.ProductionYear || (tmdbData?.release_date || tmdbData?.first_air_date || '').slice(0, 4)
  const runtime = item.RunTimeTicks ? formatRuntime(item.RunTimeTicks) : null
  const community = item.CommunityRating ?? tmdbData?.vote_average
  const cast = (tmdbData?.credits?.cast || []).slice(0, 6)
  const genres = item.Genres || []

  const isLocal = !!item.Id && !String(item.Id).startsWith('tmdb-')

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.18 }}
          onClick={close}
          className="fixed inset-0 z-[80] grid place-items-center bg-black/65 backdrop-blur-sm p-6"
          role="dialog"
          aria-label={`Quick look at ${item.Name}`}
        >
          <motion.div
            initial={{ y: 20, scale: 0.97 }}
            animate={{ y: 0, scale: 1 }}
            exit={{ y: 20, scale: 0.97 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            onClick={e => e.stopPropagation()}
            className="relative w-full max-w-2xl rounded-2xl overflow-hidden bg-surface ring-1 ring-border-strong shadow-[0_30px_80px_-20px_rgba(0,0,0,0.85)]"
          >
            <button
              onClick={close}
              aria-label="Close"
              className="absolute top-3 right-3 z-10 w-8 h-8 grid place-items-center rounded-full bg-black/55 backdrop-blur text-white/85 hover:bg-black/75 transition focus-ring"
            >
              <X size={14} stroke={2} />
            </button>

            {heroImg && (
              <div className="relative aspect-[16/8] overflow-hidden bg-elevated">
                <img src={heroImg} alt={item.Name || ''} className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-gradient-to-t from-surface via-surface/50 to-transparent" />
                {logoUrl && (
                  <img
                    src={logoUrl}
                    alt={item.Name || ''}
                    className="absolute bottom-4 left-1/2 -translate-x-1/2 h-auto max-h-20 md:max-h-24 max-w-[520px] w-auto drop-shadow-[0_4px_32px_rgba(0,0,0,0.9)]"
                    onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
                  />
                )}
              </div>
            )}

            <div className="p-6 relative">
              {!logoUrl && (
                <h2 className="text-[22px] font-display font-bold tracking-tight text-text-1 mb-2 leading-tight">
                  {item.Name}
                </h2>
              )}
              <div className="flex items-center gap-2 text-[11.5px] text-text-3 mb-4 flex-wrap font-medium">
                {year && <span className="tabular-nums">{year}</span>}
                {year && (runtime || community) && <Dot />}
                {runtime && (
                  <span className="inline-flex items-center gap-1 tabular-nums">
                    <Clock size={11} stroke={2} />
                    {runtime}
                  </span>
                )}
                {community && (
                  <>
                    {runtime && <Dot />}
                    <span className="inline-flex items-center gap-1">
                      <Star size={11} className="text-accent" fill="currentColor" stroke={0} />
                      <span className="tabular-nums">{Number(community).toFixed(1)}</span>
                    </span>
                  </>
                )}
              </div>

              {genres.length > 0 && (
                <div className="flex flex-wrap gap-1.5 mb-4">
                  {genres.slice(0, 4).map(g => (
                    <span
                      key={g}
                      className="inline-flex items-center h-6 px-2.5 bg-elevated/70 text-text-2 text-[10.5px] rounded-full ring-1 ring-border tracking-tight"
                    >
                      {g}
                    </span>
                  ))}
                </div>
              )}

              {overview && (
                <p className="text-[13.5px] text-text-2 leading-relaxed line-clamp-4 mb-5">
                  {overview}
                </p>
              )}

              {cast.length > 0 && (
                <div className="mb-5">
                  <p className="text-[10px] uppercase tracking-[0.16em] font-semibold text-text-4 mb-2">
                    Cast
                  </p>
                  <p className="text-[12.5px] text-text-2 leading-snug">
                    {cast.map((c, i) => (
                      <span key={c.id}>
                        <span className="font-medium text-text-1">{c.name}</span>
                        {c.character && <span className="text-text-4"> as {c.character}</span>}
                        {i < cast.length - 1 && <span className="text-text-5 mx-1.5">·</span>}
                      </span>
                    ))}
                  </p>
                </div>
              )}

              <div className="flex items-center gap-2.5 flex-wrap">
                {isLocal && (
                  <button
                    onClick={() => {
                      close()
                      navigate(`/play/${item.Id}`)
                    }}
                    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" />
                    Play
                  </button>
                )}
                <button
                  onClick={() => {
                    close()
                    if (item.Id) navigate(`/item/${item.Id}`)
                  }}
                  className="inline-flex items-center gap-2 h-11 px-5 rounded-full bg-white/8 hover:bg-white/14 text-text-1 text-[13px] font-medium tracking-tight border border-border hover:border-border-strong transition focus-ring"
                >
                  <Info size={14} stroke={2} />
                  More info
                </button>
                {isLocal && item.Id && (item.Type === 'Movie' || item.Type === 'Series') && (
                  <WatchlistButton itemId={item.Id} />
                )}
                {numericTmdb && (item.Type === 'Movie' || item.Type === 'Series') && (
                  <RequestButton
                    tmdbId={numericTmdb}
                    kind={item.Type === 'Movie' ? 'movie' : 'tv'}
                    tmdbData={(tmdbData || null) as (import('../../api/tmdb').TmdbMovie | import('../../api/tmdb').TmdbTvShow | null)}
                  />
                )}
              </div>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

function Dot() {
  return <span className="text-text-5">·</span>
}
