import { Skeleton } from "@/components/Skeleton";
import SkeletonLoader from "@/components/Skeleton/Skeleton";
import { GlobalContext, showToast } from "@/context/Global";
import MkdSDK from "@/utils/MkdSDK";
import React 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 { MdFullscreen } from "react-icons/md";
import { useSearchParams } from "react-router-dom";

// pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

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

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

const Docs = ({
  width,
  height,
  url = "",
  saveData,
  loading,
  isLoadingPdf,
  setIsLoadingPdf,
  setIsFullView,
  numPages,
  pageNumber,
  iframeRef,
  previousPage,
  nextPage,
  fileUrl,
  onDocumentLoadSuccess,
  pdfLoadSuccess,
  changePage,
  isCreateSection,
  changedPdf,
  setChangedPdf,
  saveTranscribeLoading,
}) => {
  const [fileObj, setFileObj] = React.useState({});
  const [isUpdating, setIsUpdating] = React.useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [typedValue, setTypedValue] = React.useState(null);
  const [searchParams] = useSearchParams();
  const pdfParam = searchParams.get("pdf");

  const pdf_url =
    (url?.includes("pdf_file") ? JSON.parse(url)?.pdf_file : url) ?? null;

  const previewImage = async (field, target) => {
    let tempFileObj = fileObj;
    const fileName = target.files[0].name;
    tempFileObj[field] = {
      file: target.files[0],
      tempURL: URL.createObjectURL(target.files[0]),
    };
    setFileObj({ ...tempFileObj });
    setChangedPdf(true);
    await submitPdf(fileName);
  };

  const submitPdf = async (fileName) => {
    let sdk = new MkdSDK();
    setIsUpdating(true);
    // setIsLoadingPdf(true);
    try {
      let imgUrl;
      let formData = new FormData();
      formData.append("file", fileObj["pdf_file"].file);
      let uploadResult = await sdk.uploadImage(formData);
      imgUrl = uploadResult.url;
      saveData("pdf_file", imgUrl, fileName);

      // showToast(globalDispatch, "Changed PDF");
    } catch (error) {
      showToast(globalDispatch, "Failed to change PDF");
    } finally {
      setIsUpdating(false);
      setIsLoadingPdf(false);
    }
  };

  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);
    }
  };

  return (
    <>
      {changedPdf && (isLoadingPdf || loading) ? (
        <Skeleton count={3} counts={[1, 1, 1]} />
      ) : pdf_url?.length ? (
        <div>
          <div
            className={`${
              isCreateSection
                ? "hidden"
                : "flex flex-col items-center justify-stretch"
            }`}
          >
            {/* {loading && !iframeRef.current && < SkeletonLoader />} */}
            {/* <iframe ref={iframeRef} onLoad={() => setLoading(false)} className="w-full h-[500px]" src="https://drive.google.com/uc?id=1Sdi2IvDoRLACWoiSKLaDE6H0lm_kWjhr" title="preview my file on nav"></iframe> */}
            {/* <iframe ref={iframeRef} onLoad={() => setLoading(false)} className="w-full h-[500px]" src="https://drive.google.com/file/d/1Sdi2IvDoRLACWoiSKLaDE6H0lm_kWjhr/preview" title="preview my file on nav "></iframe> */}
            {pdfLoadSuccess ? (
              <div className="mx-auto mb-3 flex w-[50%] flex-col items-center justify-center space-y-3 text-center">
                <div className="flex items-center justify-between gap-4">
                  <button
                    className="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="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="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={
                    pdfParam === "0"
                      ? "hidden"
                      : "flex items-center justify-center gap-16"
                  }
                >
                  <button
                    className="relative flex max-w-[100px] cursor-pointer items-center justify-center self-end whitespace-nowrap rounded-md bg-[#4F46E5] px-3 py-2 text-white shadow-sm"
                    disabled={isUpdating}
                  >
                    <span>
                      {isUpdating ? "Changing" : "Change"}
                      &nbsp; PDF
                    </span>
                    <input
                      type="file"
                      accept=".pdf"
                      className="absolute left-0 top-0 flex h-full w-full opacity-0"
                      onChange={(e) => previewImage("pdf_file", e.target)}
                    />
                  </button>
                </div>
              </div>
            ) : (
              <></>
            )}

            <div
              className={`${
                pdfLoadSuccess && pdfParam !== "0"
                  ? "relative rounded-md border border-[#888888]"
                  : "hidden"
              }`}
            >
              <button
                title="Full Screen"
                className={
                  pdfLoadSuccess
                    ? "absolute left-[0] top-[0] z-10 m-4 block cursor-pointer rounded-md border border-[#C6C6C6] bg-[#f4f4f4] px-3 py-2 shadow-sm"
                    : "hidden"
                }
                onClick={() => setIsFullView(true)}
                type="button"
              >
                <MdFullscreen />
              </button>
              <Document
                className={"!max-w-[400px]"}
                ref={iframeRef}
                file={fileUrl()}
                onLoadSuccess={onDocumentLoadSuccess}
                options={options}
                loading={<SkeletonLoader />}
                height={height}
                width={width}
              >
                <Page
                  // key={`page_${index + 1}`}
                  // pageIndex={index + 1}
                  className={"!min-w-[250px]"}
                  loading={<SkeletonLoader />}
                  pageNumber={pageNumber}
                  height={height - 100}
                  width={width}
                />
              </Document>
            </div>
            <div className={pdfLoadSuccess ? "hidden" : "block w-full"}>
              <Skeleton count={4} counts={[1, 2]} />
            </div>
          </div>
        </div>
      ) : (
        <div className="mx-5 my-5 flex min-h-[30vh] items-center justify-center gap-4 rounded-md bg-gray-100">
          <button
            className="relative my-auto flex max-w-[100px] cursor-pointer items-center justify-center self-end whitespace-nowrap rounded-md bg-[#4F46E5] px-5 py-2 text-white shadow-sm"
            disabled={isUpdating}
          >
            <span>
              {isUpdating ? "Uploading" : "Upload"}
              &nbsp; PDF
            </span>
            <input
              type="file"
              accept=".pdf"
              className="absolute left-0 top-0 flex h-full w-full opacity-0"
              onChange={(e) => previewImage("pdf_file", e.target)}
            />
          </button>
        </div>
      )}
    </>
  );
};

export default Docs;
