"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import {
  ZoomIn,
  ZoomOut,
  Download,
  X,
  FileText,
} from "lucide-react";
import { Loading } from "@/components/ui/loading";
import dynamic from "next/dynamic";

const PdfDoc = dynamic(
  () => import("./pdf-viewer-document").then((m) => m.PdfViewerDocument),
  {
    ssr: false,
    loading: () => (
      <Loading
        layout="section"
        className="py-40"
        size="lg"
        spinnerClassName="text-[#6C63FF]"
        message="Initializing PDF engine…"
      />
    ),
  }
);

const PdfPager = dynamic(
  () => import("./pdf-viewer-document").then((m) => m.PdfViewerPager),
  { ssr: false }
);

interface PdfViewerDialogProps {
  url: string | null;
  fileName?: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  canDownload?: boolean;
  token?: string | null;
}


/** Loads pdfjs only after open — avoids Webpack + pdf.mjs "defineProperty on non-object" on page load. */
export function PdfViewerDialog({
  url,
  fileName,
  open,
  onOpenChange,
  canDownload = false,
  token,
}: PdfViewerDialogProps) {
  const [numPages, setNumPages] = React.useState<number>(0);
  const [pageNumber, setPageNumber] = React.useState<number>(1);
  const [scale, setScale] = React.useState<number>(1.0);
  const [docLoadError, setDocLoadError] = React.useState(false);

  const isPdf = React.useMemo(() => {
    const check = (s?: string | null) => {
      if (!s) return false;
      const lower = s.toLowerCase();
      return (
        lower.endsWith(".pdf") ||
        lower.includes("application/pdf") ||
        s.startsWith("data:application/pdf")
      );
    };
    return check(url) || check(fileName);
  }, [url, fileName]);

  React.useEffect(() => {
    if (!open) {
      setNumPages(0);
      setPageNumber(1);
      setDocLoadError(false);
    }
  }, [open]);

  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!open) return;
      if (e.key === "ArrowLeft")
        setPageNumber((prev) => Math.max(prev - 1, 1));
      if (e.key === "ArrowRight")
        setPageNumber((prev) => Math.min(prev + 1, numPages));
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [open, numPages]);

  // No longer needed: const PdfDoc = DocModule?.PdfViewerDocument;
  // No longer needed: const PdfPager = DocModule?.PdfViewerPager;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent 
        showCloseButton={false}
        className="max-w-[95vw] lg:max-w-4xl h-[90vh] flex flex-col p-0 overflow-hidden rounded-2xl border-none shadow-2xl bg-white/95 backdrop-blur-xl"
      >
        <DialogHeader className="p-4 border-b border-gray-100 flex flex-row items-center justify-between bg-white/50 shrink-0">
          <div className="flex flex-col min-w-0 pr-4">
            <DialogTitle className="text-lg font-bold text-gray-900 font-['Lexend'] truncate">
              {fileName || "PDF Viewer"}
            </DialogTitle>
            {numPages > 0 && (
              <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest font-['Lexend_Deca']">
                Page {pageNumber} of {numPages}
              </p>
            )}
          </div>

          <div className="flex items-center gap-2">
            <div className="hidden sm:flex items-center bg-gray-100 rounded-xl p-0.5 mr-2">
              <Button
                variant="ghost"
                size="icon"
                onClick={(e) => {
                  e.stopPropagation();
                  setScale((prev) => Math.max(prev - 0.1, 0.5));
                }}
                className="size-8 rounded-lg hover:bg-white text-gray-500"
                title="Zoom Out"
              >
                <ZoomOut size={16} />
              </Button>
              <span className="text-[11px] font-bold w-12 text-center text-gray-600 select-none">
                {Math.round(scale * 100)}%
              </span>
              <Button
                variant="ghost"
                size="icon"
                onClick={(e) => {
                  e.stopPropagation();
                  setScale((prev) => Math.min(prev + 0.1, 2.0));
                }}
                className="size-8 rounded-lg hover:bg-white text-gray-500"
                title="Zoom In"
              >
                <ZoomIn size={16} />
              </Button>
            </div>

            <Button
              variant="ghost"
              size="icon"
              onClick={() => onOpenChange(false)}
              className="rounded-xl size-9 hover:bg-gray-100 ml-1"
            >
              <X size={18} className="text-gray-400" />
            </Button>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-auto bg-gray-50/50 p-4 sm:p-8 flex justify-center items-start scrollbar-thin scrollbar-thumb-gray-200 select-none">
          {url &&
            (!isPdf ? (
              <div className="flex flex-col items-center justify-center py-20 bg-white rounded-3xl border border-gray-100 px-10 text-center max-w-md mx-auto mt-20 shadow-sm animate-in fade-in zoom-in duration-300">
                <div className="size-20 rounded-3xl bg-[#6C63FF]/5 flex items-center justify-center text-[#6C63FF] mb-6 shadow-inner">
                  <FileText size={40} />
                </div>
                <h3 className="text-xl font-bold text-gray-900 font-['Lexend']">
                  Preview Unavailable
                </h3>
                <p className="text-sm mt-3 text-gray-500 leading-relaxed font-medium font-['Lexend']">
                  The file <b>{fileName || "document"}</b> is not a PDF and cannot be previewed directly in the browser.
                </p>
                {canDownload && (
                  <Button
                    variant="default"
                    size="lg"
                    className="mt-8 rounded-2xl bg-[#6C63FF] hover:bg-[#5b54d6] text-white px-8 font-bold shadow-lg shadow-[#6C63FF]/20 transition-all hover:scale-105 active:scale-95"
                    onClick={() => window.open(url, "_blank")}
                  >
                    <Download size={18} className="mr-2" />
                    Download to View
                  </Button>
                )}
              </div>
            ) : docLoadError ? (
              <div className="flex flex-col items-center justify-center py-20 text-red-500 bg-red-50 rounded-2xl border border-red-100 px-10 text-center max-w-sm mx-auto mt-20">
                <p className="text-sm font-medium">
                  PDF rendering failed. The file may be corrupt or inaccessible.
                </p>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-4 border-red-200 text-red-600 hover:bg-red-100"
                  onClick={() => window.open(url, "_blank")}
                >
                  Open in New Tab
                </Button>
              </div>
            ) : (
              <PdfDoc
                url={url}
                token={token}
                canDownload={canDownload}
                onNumPages={(n) => {
                  setNumPages(n);
                  setPageNumber(1);
                }}
                pageNumber={pageNumber}
                scale={scale}
                onError={() => setDocLoadError(true)}
              />
            ))}
        </div>

        {PdfPager && url && PdfDoc && !docLoadError && (
          <PdfPager
            pageNumber={pageNumber}
            numPages={numPages}
            onPrev={() => setPageNumber((p) => Math.max(p - 1, 1))}
            onNext={() => setPageNumber((p) => Math.min(p + 1, numPages))}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}
