"use client"

import { useState, useMemo, useCallback, useEffect, useRef } from "react"
import { Document, Page, pdfjs } from "react-pdf"
import "react-pdf/dist/Page/AnnotationLayer.css"
import "react-pdf/dist/Page/TextLayer.css"
import {
  ChevronLeft,
  ChevronRight,
  ZoomIn,
  ZoomOut,
  FileText,
} from "lucide-react"
import { Button } from "../ui/button"

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url
).toString()

const MIN_SCALE = 0.5
const MAX_SCALE = 2.5
const SCALE_STEP = 0.25

export default function PDFReader({ fileUrl, title }: { fileUrl: string, title: string }) {
  const [numPages, setNumPages] = useState<number>(0)
  const [pageNumber, setPageNumber] = useState(1)
  const [scale, setScale] = useState(1.0)
  const containerRef = useRef<HTMLDivElement>(null)
  const [containerWidth, setContainerWidth] = useState<number>(0)

  const options = useMemo(() => ({
    cMapUrl: "/cmaps/",
    cMapPacked: true,
  }), [])

  useEffect(() => {
    if (!containerRef.current) return

    const observer = new ResizeObserver(entries => {
      const width = entries[0]?.contentRect.width
      if (width) setContainerWidth(width)
    })

    observer.observe(containerRef.current)
    return () => observer.disconnect()
  }, [])

  const goToPrev = useCallback(() => setPageNumber(p => Math.max(1, p - 1)), [])
  const goToNext = useCallback(() => setPageNumber(p => Math.min(numPages, p + 1)), [numPages])
  const zoomIn = useCallback(() => setScale(s => Math.min(MAX_SCALE, s + SCALE_STEP)), [])
  const zoomOut = useCallback(() => setScale(s => Math.max(MIN_SCALE, s - SCALE_STEP)), [])

  return (
    <div className="flex flex-col h-screen bg-[#1a1a1a]">

      {/* ── Toolbar ─────────────────────────────────── */}
      <div className="flex items-center justify-between px-6 py-2 bg-[#2a2a2a] border-b border-white/10 shrink-0">

        {/* Left — file info */}
        <div className="flex items-center gap-2 text-white/50">
          <FileText className="size-4" />
          <span className="text-xs font-medium tracking-wide truncate max-w-[200px]">
            {title}
          </span>
        </div>

        {/* Center — navigation */}
        <div className="flex items-center gap-1">
          <ToolbarButton onClick={goToPrev} disabled={pageNumber <= 1}>
            <ChevronLeft className="size-4" />
          </ToolbarButton>

          <div className="flex items-center gap-1.5 px-3 py-1 rounded bg-white/10 text-white text-xs font-mono min-w-[90px] justify-center">
            <span>{pageNumber}</span>
            <span className="text-white/30">/</span>
            <span className="text-white/60">{numPages}</span>
          </div>

          <ToolbarButton onClick={goToNext} disabled={pageNumber >= numPages}>
            <ChevronRight className="size-4" />
          </ToolbarButton>
        </div>

        {/* Right — zoom */}
        <div className="flex items-center gap-1">
          <ToolbarButton onClick={zoomOut} disabled={scale <= MIN_SCALE}>
            <ZoomOut className="size-4" />
          </ToolbarButton>

          <div className="px-3 py-1 rounded bg-white/10 text-white text-xs font-mono min-w-[52px] text-center">
            {Math.round(scale * 100)}%
          </div>

          <ToolbarButton onClick={zoomIn} disabled={scale >= MAX_SCALE}>
            <ZoomIn className="size-4" />
          </ToolbarButton>
        </div>

      </div>

      {/* ── PDF Viewport ─────────────────────────────── */}
      <div ref={containerRef} className="flex-1 overflow-auto flex justify-center py-8 px-4">
        <Document
          file={fileUrl}
          onLoadSuccess={({ numPages }) => setNumPages(numPages)}
          options={options}
        >
          <Page
            pageNumber={pageNumber}
            width={containerWidth ? containerWidth - 32 : undefined}
            scale={scale}
            renderAnnotationLayer={false}
            renderTextLayer={false}
            className="shadow-2xl"
          />
        </Document>
      </div>


      {/* ── Bottom bar — keyboard hint ───────────────── */}
      <div className="flex items-center justify-center py-2 bg-[#2a2a2a] border-t border-white/10 shrink-0">
        <p className="text-[10px] text-white/20 tracking-widest uppercase">
          Use arrows to navigate pages
        </p>
      </div>

    </div>
  )
}

// reusable toolbar button
function ToolbarButton({
  onClick,
  disabled,
  children,
}: {
  onClick: () => void
  disabled: boolean
  children: React.ReactNode
}) {
  return (
    <Button
      onClick={onClick}
      disabled={disabled}
      type="button"
      className="flex items-center justify-center size-8 rounded text-white/70 hover:bg-white/10 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
    >
      {children}
    </Button>
  )
}