import SkeletonLoader from "@/components/Skeleton/Skeleton";
import React, { useRef, useState } from "react";
import { pdfjs, Document, Page } from "react-pdf";
import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "react-pdf/dist/esm/Page/TextLayer.css";
import { TiZoomIn, TiZoomOut } from "react-icons/ti";
import { MdFullscreenExit } from "react-icons/md";

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

const options = {
  cMapUrl: "/cmaps/",
  standardFontDataUrl: "/standard_fonts/",
};

const MIN_SCALE = 1.0; // Define a minimum scale value

const PDFViewer = ({
  setIsFullView,
  numPages,
  pageNumber,
  iframeRef,
  previousPage,
  nextPage,
  fileUrl,
  onDocumentLoadSuccess,
  changePage,
  saveTranscribeLoading,
  isFullView,
}) => {
  const [scale, setScale] = React.useState(1);
  const [typedValue, setTypedValue] = React.useState(null);
  const [isScrolling, setIsScrolling] = useState(false);
  const [scrollPosition, setScrollPosition] = useState({ left: 0, top: 0 });
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const scrollerRef = useRef(null);

  const changeZoom = (newScale) => {
    if (newScale < MIN_SCALE) {
      newScale = MIN_SCALE; // Ensure the scale does not go below the minimum
    }
    setScale(newScale);
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };



  const toggleScrolling = (isEnable) => {
    setIsScrolling(isEnable);
    if (isEnable) {
      window.addEventListener("mousemove", onMouseMove);
      window.addEventListener("mouseup", onMouseUp);
    } else {
      window.removeEventListener("mousemove", onMouseMove);
    }
  };

  const onMouseMove = (event) => {
    const { clientX, clientY } = event;
    const { left, top } = scrollerRef.current.getBoundingClientRect();
    const deltaX = (clientX - mousePosition.x) / scale; // Adjust for scale
    const deltaY = (clientY - mousePosition.y) / scale; // Adjust for scale
    setMousePosition({ x: clientX, y: clientY });
    setScrollPosition((prevScrollPosition) => ({
      left: prevScrollPosition.left + deltaX,
      top: prevScrollPosition.top + deltaY,
    }));
    scrollerRef.current.scrollLeft = scrollPosition.left + deltaX;
    scrollerRef.current.scrollTop = scrollPosition.top + deltaY;
  };

  const onMouseUp = () => {
    setIsScrolling(false);
    window.removeEventListener("mousemove", onMouseMove);
    window.removeEventListener("mouseup", onMouseUp); 
  };

  const onMouseDown = (event) => {
    const { scrollLeft, scrollTop } = scrollerRef.current;
    setScrollPosition({ left: scrollLeft, top: scrollTop });
    setMousePosition({ x: event.clientX, y: event.clientY });
    toggleScrolling(true);
  };

  const handleKeyDown = (event) => {
    if (event.key === "Escape") {
      setIsFullView(false);
    }
  };
  document.addEventListener("keydown", handleKeyDown);

  if (isFullView) {
    const intervel = setInterval(() => {
      setTimeout(() => {
        if (document.fullscreenElement) {
          setIsFullView(true);
        } else {
          setIsFullView(false);
          clearInterval(intervel);
        }
      }, 50);
    }, 800);
  }

  const handlePageNumChange = (event) => {
    let value = event.target.value.replace(/\D/g, "");
    value = Number(value);
    if (Number(numPages) < value) {
      setTypedValue(Number(numPages));
    } else {
      setTypedValue(value);
    }

    if (event.key === "Enter") {
      changePage(value, "input");
      setTypedValue(null);
    }
  };

  const onDoubleClick = (event) => {
    event.preventDefault();
  }
 
  return (
    <div className="mb-[-10%] ">
      <div className="my-3 flex items-center justify-center gap-5">
        <button
          title="Zoom out"
          className="cursor-pointer rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-3 py-2 shadow-sm"
          onClick={() => changeZoom(scale - 0.1)}
          type="button"
        >
          <TiZoomOut />
        </button>
        <button
          title="Exit Full Screen"
          className="cursor-pointer rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-3 py-2 shadow-sm"
          onClick={() => setIsFullView(false)}
          type="button"
        >
          <MdFullscreenExit />
        </button>
        <button
          title="Zoom in"
          className="cursor-pointer rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-3 py-2 shadow-sm"
          onClick={() => changeZoom(scale + 0.1)}
          type="button"
        >
          <TiZoomIn />
        </button>
      </div>
      <div className="my-3 flex items-center justify-center gap-4">
        <button
          className="!z-10 flex max-w-[100px] cursor-pointer items-center rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-4 py-2 shadow-sm  disabled:cursor-not-allowed"
          disabled={(pageNumber || 0) <= 1 || saveTranscribeLoading}
          onClick={previousPage}
          type="button"
        >
          &lt;
        </button>
        <div className="flex min-w-[6.5rem] items-center gap-2">
          <span>Page</span>
          <input
            type="text"
            placeholder={pageNumber}
            value={typedValue !== null ? typedValue : pageNumber}
            onChange={(e) => handlePageNumChange(e)}
            onKeyDown={(e) => handlePageNumChange(e)}
            className="!z-20 flex w-[50px] items-center rounded-md border border-[#C6C6C6] bg-white px-3 text-center placeholder-slate-950  shadow-sm"
            disabled={saveTranscribeLoading}
          />
          <span>{`of ${numPages || "--"}`}</span>
        </div>

        <button
          className="!z-20 flex max-w-[100px] cursor-pointer items-center rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-4 py-2 shadow-sm  disabled:cursor-not-allowed"
          disabled={
            (pageNumber || 0) >= (numPages || 0) || saveTranscribeLoading
          }
          onClick={nextPage}
          type="button"
        >
          &gt;
        </button>
      </div>

      <div
 
        className="mx-auto !max-h-[60vh] !w-[70vw] overflow-auto"
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          overflowX: "auto", // Enable horizontal scrolling
          overflowY: "auto", // Enable vertical scrolling
          WebkitOverflowScrolling: "touch",
          msOverflowStyle: "scrollbar",
          scrollbarWidth: "thin", // Use a thinner scrollbar for better UX
          cursor: "auto", // Change cursor when scrolling
        }}
      >
        <div
          className="flex justify-center"
          style={{
            transform: `scale(${scale})`, // Dynamically apply the zoom scale
            transformOrigin: "left top", // Ensure scaling happens from the center-top
            transformBox: "fill-box",
          }}
        >
          <Document
            className="hover:cursor-auto"
            ref={iframeRef}
            file={fileUrl()}
            onLoadSuccess={onDocumentLoadSuccess}
            options={options}
            loading={<SkeletonLoader />}
            onDoubleClick={onDoubleClick}
          >
            <Page
              pageNumber={pageNumber}
              scale={1} // Set the Page scale to 1 since we're scaling the container
              loading={<SkeletonLoader />}
              onDoubleClick={onDoubleClick}
            />
          </Document>
        </div>
      </div>
    </div>
  );
};

export default PDFViewer;
