import React, { useCallback, useEffect, useRef, useState } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import CV from "./CV";
import { useUploadDocuments } from "../../../../utils/hooks/useUploadDocuments";
import UseFullScreenLoader from "../../../../hooks/UseFullScreenLoader";
import Swal from "sweetalert2";

const Home = () => {
  const cvRef = useRef();
  const [getLoading, setLoading] = useState<boolean>(false);
  const [uploadedDocUrl, setUploadedDocUrl] = useState<string>("");
  const [getCVData, setCVData] = useState<any>(null);

  useEffect(() => {
    getDVFromLocalStorage();
  }, []);

  useEffect(() => {
    // Upload the optimized PDF file
    (async function () {
      if (getCVData != null) {
        const input = cvRef.current;

        if (input) {
          setLoading(true); // setting the loading as true when the system started genertaing the cv as a pdf
          const pdf = new jsPDF("p", "mm", "a4");
          const pdfWidth = pdf.internal.pageSize.getWidth();
          const pdfHeight = pdf.internal.pageSize.getHeight();
          const pdfMargin = 5; // Margin for the PDF
          const canvasWidth = pdfWidth - 2 * pdfMargin;
          const canvasHeight = pdfHeight - 2 * pdfMargin;

          // Function to create PDF pages from canvas
          const createPdfPages = async (input: any) => {
            const canvas = await html2canvas(input, { scale: 2 }); // Increase scale for higher quality
            const totalHeight = canvas.height;
            let position = 0;

            while (position < totalHeight) {
              const canvasPage = document.createElement("canvas");
              canvasPage.width = canvas.width;
              canvasPage.height = canvasHeight * (canvas.width / canvasWidth);
              const ctx = canvasPage.getContext("2d");

              ctx?.drawImage(
                canvas,
                0,
                position,
                canvas.width,
                canvasHeight * (canvas.width / canvasWidth),
                0,
                0,
                canvasPage.width,
                canvasPage.height
              );

              const imgData = canvasPage.toDataURL("image/jpeg", 0.75); // Use JPEG and reduce quality to 0.75

              if (position > 0) {
                pdf.addPage();
              }
              pdf.addImage(
                imgData,
                "JPEG",
                pdfMargin,
                pdfMargin,
                canvasWidth,
                canvasHeight
              );
              position += canvasHeight * (canvas.width / canvasWidth);
            }

            const pdfBlob = pdf.output("blob");
            const pdfFile = new File([pdfBlob], "cv.pdf", {
              type: "application/pdf",
            });
            try {
              const { resp, status } = (await useUploadDocuments(
                pdfFile,
                "System CV",
                "6"
              )) as Response;
              setUploadedDocUrl(resp.files[0].url);
              setLoading(false);
              if (status === 200) {
                await Swal.fire({
                  title: "Success!",
                  text: "CV Uploaded Successfully!",
                  icon: "success",
                  confirmButtonColor: "#055875",
                  iconColor: "#055875",
                });
              } else if (status == 500) {
                await Swal.fire({
                  title: "Failed!",
                  text: "Server Error Occurred!",
                  icon: "warning",
                  confirmButtonColor: "#055875",
                  iconColor: "#055875",
                });
              }
            } catch (error) {
              setLoading(false);
              console.error("Error uploading file:", error);
              await Swal.fire({
                title: "Failed!",
                text: "Failed to Upload the CV to our server!",
                icon: "warning",
                confirmButtonColor: "#055875",
                iconColor: "#055875",
              });
            } finally {
              setLoading(false);
            }
          };

          createPdfPages(input);
        }
      }
    })();
    console.log("PDF FILE ISsssss=>", getCVData);
  }, [getCVData]);

  const getDVFromLocalStorage = () => {
    try {
      const cvData = JSON.parse(localStorage.getItem("cvData")!);
      console.log(cvData);
      setCVData(cvData);
    } catch (err) {
      console.log("Error getting the Cv Data from the LocalStorage: ", err);
    }
  };

  const handleDownloadPDF = () => {
    const input = cvRef.current;
    const cvName = getCVData.firstName;

    if (input) {
      const pdf = new jsPDF("p", "mm", "a4");
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const pdfMargin = 5; // Margin for the PDF
      const canvasWidth = pdfWidth - 2 * pdfMargin;
      const canvasHeight = pdfHeight - 2 * pdfMargin;

      // Function to create PDF pages from canvas
      const createPdfPages = async (input: any) => {
        const canvas = await html2canvas(input, { scale: 1 }); // Reduce scale for lower resolution
        const totalHeight = canvas.height;
        let position = 0;

        while (position < totalHeight) {
          const canvasPage = document.createElement("canvas");
          canvasPage.width = canvas.width;
          canvasPage.height = canvasHeight * (canvas.width / canvasWidth);
          const ctx = canvasPage.getContext("2d");

          ctx?.drawImage(
            canvas,
            0,
            position,
            canvas.width,
            canvasHeight * (canvas.width / canvasWidth),
            0,
            0,
            canvasPage.width,
            canvasPage.height
          );

          const imgData = canvasPage.toDataURL("image/jpeg", 0.75); // Use JPEG and reduce quality to 0.75

          if (position > 0) {
            pdf.addPage();
          }
          pdf.addImage(
            imgData,
            "JPEG",
            pdfMargin,
            pdfMargin,
            canvasWidth,
            canvasHeight
          );
          position += canvasHeight * (canvas.width / canvasWidth);
        }

        pdf.save(`${cvName}_CV.pdf`);
      };

      createPdfPages(input);
    }
  };

  return (
    <>
      {getLoading && (
        <UseFullScreenLoader text="Uploading the CV to Server..." />
      )}
      <div className="p-4 d-flex justify-content-center align-items-center cv-mobile-scroll flex-column">
        <CV ref={cvRef} getCVData={getCVData} />
        <div className="d-flex align-items-center justify-content-between w-100 left-0 position-sticky mt-5 flex-wrap">
          <button
            onClick={handleDownloadPDF}
            className="theme-btn btn-style-one d-inline-block"
          >
            Download as PDF
          </button>
          <div className="d-flex gap-3 ">
            <div className="option-box d-flex gap-3">
              <span>Share On: </span>
              <ul className="option-list">
                <li>
                  <a
                    href={`https://facebook.com/sharer/sharer.php?u=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on Facebook"
                  >
                    <i className="fab fa-facebook-f"></i>
                  </a>
                </li>
                <li>
                  <a
                    href={`https://twitter.com/intent/tweet/?text=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on Twitter"
                  >
                    <i className="fab fa-twitter"></i>
                  </a>
                </li>
                <li>
                  <a
                    href={`https://reddit.com/submit?url=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on Reddit"
                  >
                    <i className="fab fa-reddit"></i>
                  </a>
                </li>
                <li>
                  <a
                    href={`https://www.linkedin.com/shareArticle?mini=true&url=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on LinkedIn"
                  >
                    <i className="fab fa-linkedin-in"></i>
                  </a>
                </li>
                <li>
                  <a
                    href={`mailto:?subject=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on Email"
                  >
                    <i className="far fa-envelope"></i>
                  </a>
                </li>
                <li>
                  <a
                    href={`https://api.whatsapp.com/send?text=${uploadedDocUrl}`}
                    target="_blank"
                    data-text="Share on WhatsApp"
                  >
                    <i className="fab fa-whatsapp"></i>
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Home;
