"use client"

import { useEffect, useRef, useState, useCallback } from "react"
import Epub, { Book, Rendition, NavItem } from "epubjs"
import { ChevronLeft, ChevronRight, BookOpen, List, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

export default function EPUBReader({ fileUrl }: { fileUrl: string }) {
  const viewerRef   = useRef<HTMLDivElement>(null)
  const bookRef     = useRef<Book | null>(null)
  const rendRef     = useRef<Rendition | null>(null)

  const [loading,  setLoading]  = useState(true)
  const [error,    setError]    = useState(false)
  const [toc,      setToc]      = useState<NavItem[]>([])
  const [tocOpen,  setTocOpen]  = useState(false)
  const [location, setLocation] = useState<string | null>(null)
  const [atStart,  setAtStart]  = useState(true)
  const [atEnd,    setAtEnd]    = useState(false)

  // ── Load book ─────────────────────────────────────────────────────────────
  useEffect(() => {
    if (!viewerRef.current) return

    let cancelled = false
    let bookInstance: Book | null = null

    async function load() {
      try {
        const response = await fetch(fileUrl)
        if (cancelled) return

        const buffer = await response.arrayBuffer()
        if (cancelled) return

        const book = Epub(buffer)
        bookInstance = book
        bookRef.current = book

        const rendition = book.renderTo(viewerRef.current!, {
          width:  "100%",
          height: "100%",
          flow:   "paginated",
          spread: "none",
          allowScriptedContent: true,
        } as Parameters<Book["renderTo"]>[1])
        rendRef.current = rendition

        // Track location changes for edge detection
        rendition.on("relocated", (loc: { start: { cfi: string }; atStart?: boolean; atEnd?: boolean }) => {
          if (cancelled) return
          setLocation(loc.start.cfi)
          setAtStart(!!loc.atStart)
          setAtEnd(!!loc.atEnd)
        })

        await rendition.display()
        if (cancelled) return

        setLoading(false)

        // Build TOC
        const nav = await book.loaded.navigation
        if (cancelled) return
        if (nav?.toc) setToc(nav.toc)
      } catch {
        if (!cancelled) {
          setError(true)
          setLoading(false)
        }
      }
    }

    load()
    return () => {
      cancelled = true
      bookInstance?.destroy()
      bookInstance = null
    }
  }, [fileUrl])

  // ── Navigation helpers ────────────────────────────────────────────────────
  const prev = useCallback(() => { rendRef.current?.prev() }, [])
  const next = useCallback(() => { rendRef.current?.next() }, [])

  const goTo = useCallback((href: string) => {
    rendRef.current?.display(href)
    setTocOpen(false)
  }, [])

  // Keyboard navigation
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "ArrowLeft")  prev()
      if (e.key === "ArrowRight") next()
    }
    window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [prev, next])

  // ── UI ────────────────────────────────────────────────────────────────────
  if (error) {
    return (
      <div className="flex items-center justify-center h-screen bg-neutral-950">
        <p className="text-red-400 text-sm">Failed to load book. Please try again.</p>
      </div>
    )
  }

  return (
    <div className="relative flex flex-col h-screen bg-neutral-50 dark:bg-neutral-900 select-none">

      {/* ── Top bar ── */}
      <div className="flex items-center justify-between px-4 py-2 border-b bg-white dark:bg-neutral-950 shrink-0">
        <Button
          variant="ghost" size="sm"
          onClick={() => setTocOpen((v) => !v)}
          className="gap-2 text-xs"
        >
          <List className="w-4 h-4" />
          Contents
        </Button>

        <p className="text-xs text-muted-foreground hidden sm:block">
          Use ← → keys or buttons to navigate
        </p>

        {/* placeholder for future controls */}
        <div className="w-[88px]" />
      </div>

      {/* ── Body: TOC sidebar + viewer ── */}
      <div className="flex flex-1 overflow-hidden relative">

        {/* TOC sidebar */}
        {tocOpen && (
          <aside className="w-64 shrink-0 border-r overflow-y-auto bg-white dark:bg-neutral-950 z-10">
            <div className="flex items-center justify-between px-4 py-3 border-b">
              <span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Table of Contents
              </span>
              <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setTocOpen(false)}>
                <X className="w-3.5 h-3.5" />
              </Button>
            </div>
            <ul className="py-2">
              {toc.length === 0 && (
                <li className="px-4 py-2 text-xs text-muted-foreground">No chapters found.</li>
              )}
              {toc.map((item) => (
                <li key={item.id}>
                  <button
                    onClick={() => goTo(item.href)}
                    className="w-full text-left px-4 py-2 text-sm hover:bg-accent truncate"
                  >
                    {item.label.trim()}
                  </button>
                  {item.subitems?.map((sub) => (
                    <button
                      key={sub.id}
                      onClick={() => goTo(sub.href)}
                      className="w-full text-left pl-8 pr-4 py-1.5 text-xs text-muted-foreground hover:bg-accent truncate"
                    >
                      {sub.label.trim()}
                    </button>
                  ))}
                </li>
              ))}
            </ul>
          </aside>
        )}

        {/* EPUB render target */}
        <div className="flex-1 relative overflow-hidden">

          {/* Loading overlay */}
          {loading && (
            <div className="absolute inset-0 flex items-center justify-center bg-neutral-50 dark:bg-neutral-900 z-20">
              <div className="flex items-center gap-2 text-muted-foreground text-sm">
                <BookOpen className="w-5 h-5 animate-pulse" />
                Loading book…
              </div>
            </div>
          )}

          {/* The actual epubjs render div */}
          <div
            ref={viewerRef}
            className="w-full h-full"
            style={{ visibility: loading ? "hidden" : "visible" }}
          />

          {/* ← Prev hit zone */}
          <button
            onClick={prev}
            disabled={atStart}
            aria-label="Previous page"
            className={cn(
              "absolute left-0 top-0 h-full w-16 flex items-center justify-start pl-2",
              "opacity-0 hover:opacity-100 transition-opacity",
              atStart && "cursor-default"
            )}
          >
            <ChevronLeft className={cn("w-8 h-8 text-foreground/30", atStart && "opacity-20")} />
          </button>

          {/* → Next hit zone */}
          <button
            onClick={next}
            disabled={atEnd}
            aria-label="Next page"
            className={cn(
              "absolute right-0 top-0 h-full w-16 flex items-center justify-end pr-2",
              "opacity-0 hover:opacity-100 transition-opacity",
              atEnd && "cursor-default"
            )}
          >
            <ChevronRight className={cn("w-8 h-8 text-foreground/30", atEnd && "opacity-20")} />
          </button>
        </div>
      </div>

      {/* ── Bottom navigation bar ── */}
      {!loading && (
        <div className="flex items-center justify-center gap-4 px-6 py-3 border-t bg-white dark:bg-neutral-950 shrink-0">
          <Button
            variant="outline" size="sm"
            onClick={prev}
            disabled={atStart}
            className="gap-1.5"
          >
            <ChevronLeft className="w-4 h-4" />
            Previous
          </Button>

          <Button
            variant="outline" size="sm"
            onClick={next}
            disabled={atEnd}
            className="gap-1.5"
          >
            Next
            <ChevronRight className="w-4 h-4" />
          </Button>
        </div>
      )}
    </div>
  )
}