let QRCodeViewItem;
let isCreatingEditor = false;
const DEFAULT_PHONE_NUMBER = "(123) 456-7890";
let qr_code_edited_File=undefined 

$(document).ready(function () {
  const qrId = getQueryParam("id");
  if (qrId) {
    sendQrRequest({ DataGetByIdWithJoin: "yes", id: qrId });
  } else {
    showToastMessageForDownload("id not found");
  }
});

function getQueryParam(param) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
}

function sendQrRequest(data) {
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data,
    success: function (resp) {
      if (data?.DataGetByIdWithJoin) {
        QRCodeViewItem = resp.data;
        createdViewForEditor();
      }
      if (data?.AddEditedImage) {
        console.log("image added");
      }
    },
    error: function (xhr, status, error) {
       if (xhr?.responseJSON?.error)
        showToastMessageForDownload(xhr?.responseJSON?.error);
      else showToastMessageForDownload(error);
    },
  });
}

function createImageEditorContainer() {
  return new Promise((resolve, reject) => {
    if (isCreatingEditor) {
     return reject(
        new Error("Image editor is already being created. Please wait.")
      );
    }
    isCreatingEditor = true;
    try {
      const container = document.createElement("div");
      container.id = "tui-image-editor-container";
      container.style.width = "100%"; // Example style
      container.style.height = "500px"; // Example style
      const parentElement = document.getElementById("imageEditor"); // Adjust as needed
      parentElement.innerHTML = "";
      parentElement.appendChild(container);
      parentElement.scrollIntoView({ behavior: "smooth" });
      resolve(container);
    } catch (error) {
      reject(error);
    } finally {
      isCreatingEditor = false;
    }
  });
}

function LoadEditorPreview(image) {
  createImageEditorContainer()
    .then((container) => {
      const imageEditor = new tui.ImageEditor("#tui-image-editor-container", {
        includeUI: {
          loadImage: {
            path: image,
           name: "SampleImage",
          },
          theme: {},
          initMenu: "filter",
          menuBarPosition: "bottom",
        },
        cssMaxWidth: 700,
        cssMaxHeight: 500,
        usageStatistics: false,
      });

      $(".tui-image-editor-download-btn").on("click", function (e) {
        const link = document.createElement("a");
        link.href = imageEditor.toDataURL();
        const imageData = imageEditor.toDataURL();
        fetch(imageData)
          .then((res) => res.blob())
          .then((blob) => {
            qr_code_edited_File = new File([blob], "qrcode.png", {
              type: "image/png",
            });
            const formData = new FormData();
            formData.append("AddEditedImage", true);
            formData.append("id",  QRCodeViewItem.id);
            formData.append("property_id",  sessionStorage.getItem("property_id"));
            formData.append("imageData",  qr_code_edited_File);
            saveEditedImage(formData);
          });
      });
    })
    .catch((error) => {
      console.error("Error creating image editor container:", error);
    });
}

function saveEditedImage(formData) {
  $.ajax({
    url: "/include/property_builder/qr_code/qr_code_requests.php",
    type: "post",
    data: formData,
    processData: false,
    contentType: false,
    success: function (resp) {
      showSuccessGlobalToastMessage(
        resp.message || "QR Code saved successfully"
      );
      selectedQrCodeImage = "";
      selectedQrCodeFile = null;
      $("#addQrCode").modal("hide");
    },
    error: function (xhr, status, error) {
      if (xhr?.responseJSON?.error)
        showErrorGlobalToastMessage(xhr?.responseJSON?.error);
      else showErrorGlobalToastMessage(error);
    },
  });
}

function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function createdViewForEditor() {
  const previewContainer = document.getElementById("downloadArea");
  previewContainer.innerHTML = "";
  const img = document.createElement("img");
  img.src = `/shared/serve_image.php?path=${QRCodeViewItem?.qr_image}&type=all_images`;
  img.alt = "QR Code Template Preview";
  img.style.width = "100%";
  img.style.height = "100%";
  img.style.objectFit = "contain";
  previewContainer.appendChild(img);
  return;
}

function getImage() {
  if (isCreatingEditor) {
    console.log("already creating");
    return;
  }
  const qr_design_image = `/shared/serve_image.php?path=${QRCodeViewItem?.qr_image}&type=all_images`;
  LoadEditorPreview(qr_design_image);
  isCreatingEditor = false;
}

function DownloadRightNow() {
  if (isCreatingEditor) {
    console.log("already creating");
    return;
  }
  isCreatingEditor = true;
  try {
    sendQrRequest({
      AddEditedImage: true,
      id: QRCodeViewItem.id,
      imageData: QRCodeViewItem.qr_image,
      download_original:true,
      property_id: sessionStorage.getItem("propertyId"),
    });
    isCreatingEditor = false;
    const link = document.createElement("a");
    link.href = `/shared/serve_image.php?path=${QRCodeViewItem?.qr_image}&type=all_images`;
    link.download = "QrCode.png";
    link.click();
  } catch (error) {
    isCreatingEditor = false;
  }
}

function showToastMessageForDownload(errorMessage) {
  document.getElementById("toastMessage").style.display = "block";
  document.getElementById("ErrorMessage").textContent = errorMessage;
  var toastEl = document.getElementById("myToast");
  var toast = new bootstrap.Toast(toastEl, {
    delay: 3000, // Delay in milliseconds (5000ms = 5 seconds)
    autohide: false,
  });
  toast.show();
}

function closeToastMessage() {
  const toastEl = document.getElementById("toastMessage");
  toastEl.style.display = "none";
}
