'use client';
import { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

// Worker setup — must use import.meta.url for local/Docker environments (no CDN)
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url,
).toString();

export function PdfViewer({ docId }: { docId: string }) {
  const [numPages, setNumPages] = useState(0);
  const [pageNumber, setPageNumber] = useState(1);
  const [scale, setScale] = useState(1.0);

  return (
    <div className="flex flex-col items-center gap-4">
      <div className="flex items-center gap-3 text-sm">
        <button
          onClick={() => setPageNumber(p => Math.max(1, p - 1))}
          disabled={pageNumber <= 1}
          className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-100"
        >
          Prev
        </button>
        <span>{pageNumber} / {numPages || '?'}</span>
        <button
          onClick={() => setPageNumber(p => Math.min(numPages, p + 1))}
          disabled={pageNumber >= numPages}
          className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-100"
        >
          Next
        </button>
        <button
          onClick={() => setScale(s => Math.min(3, s + 0.2))}
          className="px-3 py-1 border rounded hover:bg-gray-100"
        >
          Zoom In
        </button>
        <button
          onClick={() => setScale(s => Math.max(0.4, s - 0.2))}
          className="px-3 py-1 border rounded hover:bg-gray-100"
        >
          Zoom Out
        </button>
        <a
          href={`/api/documents/${docId}/file`}
          download
          className="px-3 py-1 border rounded hover:bg-gray-100"
        >
          Download
        </a>
      </div>

      <Document
        file={`/api/documents/${docId}/file`}
        onLoadSuccess={({ numPages }) => setNumPages(numPages)}
        className="shadow-lg"
      >
        <Page pageNumber={pageNumber} scale={scale} />
      </Document>
    </div>
  );
}
