import { Viewer, Worker } from "@react-pdf-viewer/core";
import { defaultLayoutPlugin } from "@react-pdf-viewer/default-layout";
import { fullScreenPlugin } from "@react-pdf-viewer/full-screen";
import { useState } from "react";

// Import styles
import "@react-pdf-viewer/core/lib/styles/index.css";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
import "@react-pdf-viewer/full-screen/lib/styles/index.css";

function PDFViewer({ pdfUrl, onError }: any) {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Plugin de fullscreen
  const fullScreenPluginInstance = fullScreenPlugin();

  // Plugin de layout padrão
  const defaultLayoutPluginInstance = defaultLayoutPlugin();

  const handleDocumentLoad = (e: any) => {
    setIsLoading(false);
    setError(null);
  };

  const handleLoadError = (e: any) => {
    // console.error("❌ PDFViewer: Erro ao carregar documento", e);
    setIsLoading(false);
    setError(e.message || "Erro desconhecido ao carregar PDF");
    if (onError) {
      onError(e);
    }
  };

  const handlePasswordRequired = () => {
    console.warn("🔒 PDFViewer: PDF protegido por senha");
    setError("PDF protegido por senha");
  };

  return (
    <Worker workerUrl="https://unpkg.com/pdfjs-dist@3.4.120/build/pdf.worker.min.js">
      <div style={{ height: "100%", width: "100%", position: "relative" }}>
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-2"></div>
              <div className="text-sm text-gray-600">Carregando PDF...</div>
            </div>
          </div>
        )}

        {error && (
          <div className="absolute inset-0 flex items-center justify-center bg-red-50">
            <div className="text-center p-4">
              <div className="text-red-600 font-semibold mb-2">
                ❌ Erro no PDFViewer
              </div>
              <div className="text-red-500 text-sm">{error}</div>
              <div className="text-xs text-gray-500 mt-2">
                URL: {pdfUrl?.substring(0, 100)}...
              </div>
            </div>
          </div>
        )}

        <Viewer
          fileUrl={pdfUrl}
          plugins={[defaultLayoutPluginInstance, fullScreenPluginInstance]}
          onDocumentLoad={handleDocumentLoad}
          httpHeaders={{
            Accept: "application/pdf",
            "Cache-Control": "no-cache",
          }}
          withCredentials={false}
        />
      </div>
    </Worker>
  );
}

export default PDFViewer;
