import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Plus } from '../../lib/icons'
import {
  loadBookmarks,
  removeBookmark,
  updateBookmark,
  type Bookmark,
} from '../../lib/bookmarks'

interface Props {
  open: boolean
  onClose: () => void
  itemId: string
  currentTime: number
  onJump: (timeSec: number) => void
  onAdd: () => void
  /** Bumped when the parent adds a bookmark so the panel re-reads storage. */
  refreshKey: number
}

function formatSec(sec: number): string {
  if (!Number.isFinite(sec) || sec < 0) return '0:00'
  const h = Math.floor(sec / 3600)
  const m = Math.floor((sec % 3600) / 60)
  const s = Math.floor(sec % 60)
  if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  return `${m}:${s.toString().padStart(2, '0')}`
}

export default function BookmarksPanel({
  open,
  onClose,
  itemId,
  onJump,
  onAdd,
  refreshKey,
}: Props) {
  const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
  const [editingId, setEditingId] = useState<string | null>(null)
  const [draftNote, setDraftNote] = useState('')

  useEffect(() => {
    if (!itemId) return
    setBookmarks(loadBookmarks(itemId))
  }, [itemId, refreshKey])

  function commitNote(bm: Bookmark) {
    updateBookmark(itemId, bm.id, { note: draftNote.trim() || undefined })
    setBookmarks(loadBookmarks(itemId))
    setEditingId(null)
  }

  function deleteBookmark(bm: Bookmark) {
    removeBookmark(itemId, bm.id)
    setBookmarks(loadBookmarks(itemId))
  }

  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="Bookmarks"
          >
            <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">
                Bookmarks
              </h2>
              <div className="flex items-center gap-1">
                <button
                  onClick={onAdd}
                  className="inline-flex items-center gap-1.5 h-8 px-3 rounded-full bg-accent/15 hover:bg-accent/25 text-accent text-[11.5px] font-semibold transition-colors focus-ring"
                >
                  <Plus size={13} stroke={2.25} />
                  Mark
                </button>
                <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>
              </div>
            </header>

            <div className="flex-1 overflow-y-auto content-scroll px-3 py-3 space-y-1.5">
              {bookmarks.length === 0 && (
                <div className="text-center py-12 px-4">
                  <p className="text-[13px] text-white/75 font-medium mb-1">No bookmarks yet</p>
                  <p className="text-[11.5px] text-white/45">
                    Press <kbd className="px-1 py-0.5 rounded bg-white/10 font-mono text-[10.5px]">B</kbd> while
                    watching to mark a moment.
                  </p>
                </div>
              )}
              {bookmarks.map(bm => (
                <div
                  key={bm.id}
                  className="rounded-lg border border-white/10 hover:border-white/20 hover:bg-white/5 transition-colors p-3 group"
                >
                  <div className="flex items-baseline gap-3 mb-1.5">
                    <button
                      onClick={() => onJump(bm.positionSec)}
                      className="text-[13px] font-mono font-semibold tabular-nums text-accent hover:text-accent-hover transition-colors focus-ring rounded"
                    >
                      {formatSec(bm.positionSec)}
                    </button>
                    <button
                      onClick={() => deleteBookmark(bm)}
                      className="ml-auto text-[10.5px] text-white/40 hover:text-error transition-colors opacity-0 group-hover:opacity-100"
                    >
                      Delete
                    </button>
                  </div>
                  {editingId === bm.id ? (
                    <input
                      autoFocus
                      value={draftNote}
                      onChange={e => setDraftNote(e.target.value)}
                      onBlur={() => commitNote(bm)}
                      onKeyDown={e => {
                        if (e.key === 'Enter') commitNote(bm)
                        if (e.key === 'Escape') setEditingId(null)
                      }}
                      placeholder="Add a note..."
                      className="w-full bg-void/60 border border-border rounded px-2 py-1 text-[12px] text-text-1 placeholder:text-text-4 focus:outline-none focus:border-accent/50"
                    />
                  ) : (
                    <button
                      onClick={() => {
                        setEditingId(bm.id)
                        setDraftNote(bm.note || '')
                      }}
                      className="text-left w-full text-[12px] text-white/75 hover:text-white transition-colors"
                    >
                      {bm.note || <span className="text-white/35 italic">Add a note...</span>}
                    </button>
                  )}
                </div>
              ))}
            </div>
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  )
}
