import { motion, AnimatePresence } from 'framer-motion'
import { X } from '../../lib/icons'
import { ticksToSeconds, formatTimecode } from '../../lib/format'

interface Chapter {
  Name?: string | null
  StartPositionTicks?: number | null
  ImageTag?: string | null
}

interface Props {
  open: boolean
  onClose: () => void
  chapters: Chapter[]
  itemId: string
  serverUrl: string
  currentTime: number
  onJump: (timeSec: number) => void
}

/**
 * Slide-in panel listing chapters with thumbnail + name + timecode. Same
 * pattern as EpisodesPanel: 380px from the right, glass chrome, escape /
 * backdrop click to close. The current chapter is highlighted with the
 * accent rail.
 */
export default function ChaptersPanel({
  open,
  onClose,
  chapters,
  itemId,
  serverUrl,
  currentTime,
  onJump,
}: Props) {
  const currentIdx = (() => {
    let idx = -1
    for (let i = 0; i < chapters.length; i++) {
      const t = ticksToSeconds(chapters[i].StartPositionTicks)
      if (t <= currentTime) idx = i
      else break
    }
    return idx
  })()

  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.18 }}
            onClick={onClose}
            className="absolute inset-0 z-30 bg-black/55 backdrop-blur-[2px]"
          />
          <motion.aside
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            className="absolute right-0 top-0 bottom-0 z-40 w-[380px] max-w-[85vw] bg-[#0c0a08]/96 backdrop-blur-xl border-l border-white/10 flex flex-col shadow-[0_0_60px_rgba(0,0,0,0.6)]"
            role="dialog"
            aria-label="Chapters"
          >
            <header className="shrink-0 px-5 pt-5 pb-3 border-b border-white/8 flex items-center justify-between">
              <h2 className="text-[13px] font-semibold uppercase tracking-[0.14em] text-white/85">
                Chapters
              </h2>
              <button
                onClick={onClose}
                className="w-8 h-8 grid place-items-center rounded-full text-white/70 hover:text-white hover:bg-white/10 transition-colors focus-ring"
                aria-label="Close"
              >
                <X size={16} />
              </button>
            </header>

            <div className="flex-1 overflow-y-auto content-scroll px-3 py-3 space-y-1.5">
              {chapters.length === 0 && (
                <p className="text-[12.5px] text-white/55 px-2 py-6 text-center">
                  No chapters in this item.
                </p>
              )}
              {chapters.map((c, i) => {
                const startSec = ticksToSeconds(c.StartPositionTicks)
                const isCurrent = i === currentIdx
                const thumb = c.ImageTag
                  ? `${serverUrl}/Items/${itemId}/Images/Chapter/${i}?tag=${c.ImageTag}&maxWidth=240`
                  : null
                return (
                  <button
                    key={i}
                    onClick={() => {
                      onClose()
                      onJump(startSec)
                    }}
                    className={`w-full text-left rounded-lg overflow-hidden border transition-colors duration-150 group ${
                      isCurrent
                        ? 'border-accent/70 bg-accent/8'
                        : 'border-white/10 hover:border-white/25 hover:bg-white/5 focus-ring'
                    }`}
                  >
                    <div className="flex gap-3 p-2">
                      <div className="relative shrink-0 w-[120px] aspect-video rounded-md overflow-hidden bg-black">
                        {thumb ? (
                          <img src={thumb} alt="" className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full bg-elevated grid place-items-center text-text-4 font-mono text-[11px] tabular-nums">
                            {String(i + 1).padStart(2, '0')}
                          </div>
                        )}
                        {isCurrent && (
                          <div className="absolute inset-0 grid place-items-center bg-black/45">
                            <span className="text-[10px] uppercase tracking-[0.16em] font-semibold text-accent">
                              Now
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="min-w-0 flex-1 py-0.5">
                        <p
                          className={`text-[10.5px] uppercase tracking-[0.14em] font-semibold mb-0.5 ${
                            isCurrent ? 'text-accent' : 'text-white/55'
                          }`}
                        >
                          {String(i + 1).padStart(2, '0')} · {formatTimecode(c.StartPositionTicks)}
                        </p>
                        <p
                          className={`text-[13px] font-medium leading-tight tracking-tight line-clamp-2 ${
                            isCurrent ? 'text-white' : 'text-white/90'
                          }`}
                        >
                          {c.Name || `Chapter ${i + 1}`}
                        </p>
                      </div>
                    </div>
                  </button>
                )
              })}
            </div>
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  )
}
