"use client"

import { useEffect, useRef, useState, useCallback } from "react"
import { useParams } from "next/navigation"
import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Loader2 } from "lucide-react"

export default function ReaderPage() {
  const { gid } = useParams<{ gid: string }>()
  const [page, setPage] = useState(0)
  const [pageUrls, setPageUrls] = useState<string[]>([])
  const [loading, setLoading] = useState(true)
  const [zoom, setZoom] = useState(1)
  const [error, setError] = useState("")
  const [title, setTitle] = useState("")
  const containerRef = useRef<HTMLDivElement>(null)
  const [showControls, setShowControls] = useState(true)
  const hideTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)

  useEffect(() => {
    async function load() {
      setLoading(true)
      setError("")

      try {
        const res = await fetch(`/api/proxy/galleries/${gid}/summary`)
        const data = await res.json()
        const summary = data?.data
        setTitle(summary?.title || `g/${gid}`)

        if (!summary) { setError("Gallery no encontrada"); setLoading(false); return }

        if (summary.num_pages && summary.num_pages > 0) {
          const urls: string[] = []
          for (let i = 0; i < summary.num_pages; i++) {
            urls.push(`/api/proxy/galleries/${gid}/cover`)
          }
          setPageUrls(urls)
          setLoading(false)
          return
        }
      } catch {}

      try {
        const artRes = await fetch(`/api/proxy/galleries/${gid}/artifacts`)
        const artData = await artRes.json()
        const rendered = artData?.data?.files?.rendered
        if (rendered?.length) {
          const urls = rendered.map(() => `/api/proxy/galleries/${gid}/cover`)
          setPageUrls(urls)
          setLoading(false)
          return
        }
      } catch {}

      try {
        const coverRes = await fetch(`/api/proxy/galleries/${gid}/cover`, { method: "HEAD" })
        if (coverRes.ok) {
          setPageUrls([`/api/proxy/galleries/${gid}/cover`])
          setLoading(false)
          return
        }
      } catch {}

      setError("No hay imágenes disponibles. La API del pipeline solo expone la portada.")
      setLoading(false)
    }

    load()
  }, [gid])

  const totalPages = pageUrls.length
  const goTo = useCallback((n: number) => setPage(Math.max(0, Math.min(n, totalPages - 1))), [totalPages])

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "ArrowLeft") goTo(page - 1)
      if (e.key === "ArrowRight") goTo(page + 1)
      if (e.key === "+" || e.key === "=") setZoom((z) => Math.min(z + 0.25, 3))
      if (e.key === "-") setZoom((z) => Math.max(z - 0.25, 0.25))
    }
    window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [page, goTo])

  const handleMouseMove = useCallback(() => {
    setShowControls(true)
    if (hideTimer.current) clearTimeout(hideTimer.current)
    hideTimer.current = setTimeout(() => setShowControls(false), 2000)
  }, [])

  if (loading) {
    return (
      <div className="flex items-center justify-center py-40 text-[var(--muted)]">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="mx-auto max-w-lg py-20 text-center">
        <div className="card p-8">
          <p className="mb-4 text-sm text-[var(--error)]">{error}</p>
          <p className="text-xs text-[var(--muted)] mb-4">
            La API del pipeline solo sirve la página 1 vía <code className="text-[var(--accent)]">/galleries/{"{gid}"}/cover</code>.
          </p>
          <a
            href={`/gallery/${gid}`}
            className="btn-primary"
          >
            Volver al detalle
          </a>
        </div>
      </div>
    )
  }

  return (
    <div
      className="flex h-[calc(100vh-3rem)] flex-col bg-black/40"
      onMouseMove={handleMouseMove}
    >
      <div
        className={`flex items-center justify-between border-b border-[var(--border)] bg-[var(--background)]/90 backdrop-blur-sm px-4 py-2 transition-opacity duration-300 ${
          showControls ? "opacity-100" : "opacity-0 pointer-events-none"
        }`}
      >
        <span className="truncate text-sm text-[var(--muted)]">{title}</span>
        <div className="flex items-center gap-3">
          <button onClick={() => setZoom((z) => Math.max(z - 0.25, 0.25))} className="btn-ghost p-1">
            <ZoomOut className="h-4 w-4" />
          </button>
          <span className="w-10 text-center text-xs text-[var(--muted)]">{Math.round(zoom * 100)}%</span>
          <button onClick={() => setZoom((z) => Math.min(z + 0.25, 3))} className="btn-ghost p-1">
            <ZoomIn className="h-4 w-4" />
          </button>
          {totalPages > 1 && (
            <span className="text-xs text-[var(--muted)]">{page + 1} / {totalPages}</span>
          )}
        </div>
      </div>

      <div ref={containerRef} className="flex flex-1 items-center justify-center overflow-auto">
        <div className="flex items-center gap-4 px-4">
          {totalPages > 1 && (
            <button
              onClick={() => goTo(page - 1)}
              disabled={page === 0}
              className={`rounded-full p-2 text-[var(--muted)] hover:bg-[var(--surface)] transition-all disabled:opacity-20 ${
                showControls ? "opacity-100" : "opacity-0"
              }`}
            >
              <ChevronLeft className="h-6 w-6" />
            </button>
          )}

          <img
            src={pageUrls[page]}
            alt={totalPages > 1 ? `Página ${page + 1}` : "Portada"}
            style={{ transform: `scale(${zoom})` }}
            className="max-h-[calc(100vh-8rem)] max-w-full origin-center object-contain transition-transform"
            draggable={false}
          />

          {totalPages > 1 && (
            <button
              onClick={() => goTo(page + 1)}
              disabled={page >= totalPages - 1}
              className={`rounded-full p-2 text-[var(--muted)] hover:bg-[var(--surface)] transition-all disabled:opacity-20 ${
                showControls ? "opacity-100" : "opacity-0"
              }`}
            >
              <ChevronRight className="h-6 w-6" />
            </button>
          )}
        </div>
      </div>

      {totalPages > 1 && (
        <div className={`flex justify-center gap-1.5 border-t border-[var(--border)] bg-[var(--background)]/90 backdrop-blur-sm px-4 py-2 transition-opacity duration-300 ${
          showControls ? "opacity-100" : "opacity-0 pointer-events-none"
        }`}>
          {Array.from({ length: Math.min(totalPages, 100) }).map((_, i) => (
            <button
              key={i}
              onClick={() => goTo(i)}
              className={`h-1.5 rounded-full transition-all ${
                i === page ? "w-6 bg-[var(--accent)]" : "w-1.5 bg-[var(--border)] hover:bg-[var(--muted)]"
              }`}
            />
          ))}
          {totalPages > 100 && (
            <span className="text-[10px] text-[var(--muted)] ml-1">+{totalPages - 100}</span>
          )}
        </div>
      )}

      {totalPages === 1 && (
        <div className="border-t border-[var(--border)] bg-[var(--background)]/90 backdrop-blur-sm px-4 py-2 text-center text-xs text-[var(--muted)]">
          Solo portada disponible. El pipeline solo expone la página 1 vía /cover.
        </div>
      )}
    </div>
  )
}
