import {createEvent} from "./utils/create-event";
import {
  isValidEmail,
  isValidInputTextField,
  updateStylingError
} from "./utils/validation";
import {isTouchDevice} from "./utils/helpers";

var Wick = window.Wick || {};
Wick.Quiz = {
  STYLE_QUIZ_EMAIL: 'styleQuizEmail',
  el: {
    quizContainer: ".main-quiz",
    quizActions: ".quiz-actions",
    body: 'body',
    html: 'html',
    input: 'input[type="text"]',
    modal: '.quiz-modal',
    modalEmail: '#quiz-modal',
    modalEmailFinal: '#quiz-modal-final',
    btnQuizEmail: '#email-results-quiz',
    cancelBtn: '.quiz-modal__controls .btn-cancel',
    submitBtn: '.quiz-modal__controls [type="submit"]',
    quizForm: '.quiz-modal__form',
    btnPrintResultQuiz: '#print-results-quiz',
    emailInput: '#email',
    firstNameInput: '#firstName',
    surnameInput: '#surname',
    formInvalidClass: 'form_invalid'
  },
  errorMessages: {
    errorFirstName: 'Please enter a first name',
    errorSurname: 'Please enter a surname',
    errorEmail: 'Please enter a valid email address',
  },
  getFieldsConfigurations: function () {
    return [
      {
        input: Wick.Quiz.el.firstNameInput,
        validator: isValidInputTextField,
        error: Wick.Quiz.errorMessages.errorFirstName
      },
      {
        input: Wick.Quiz.el.surnameInput,
        validator: isValidInputTextField,
        error: Wick.Quiz.errorMessages.errorSurname
      },
      {
        input: Wick.Quiz.el.emailInput,
        validator: isValidEmail,
        error: Wick.Quiz.errorMessages.errorEmail
      }
    ]
  },

  showModal: function (modalSelector) {
    $(modalSelector).modal('show');
  },

  closeModal: function(selector, event) {
    if (event) event.preventDefault();
    $(selector).modal('hide');
  },

  validateInput: function (input, validatorFunction, errorMsg) {
    const value = $(input).val();
    const isValid = validatorFunction(value);
    updateStylingError(input, isValid, errorMsg);

    return isValid;
  },

  validateForm: function() {
    const fields = Wick.Quiz.getFieldsConfigurations();
    let isValid = true;

    fields.forEach(field => {
      const result = Wick.Quiz.validateInput(field.input, field.validator, field.error);
      isValid = isValid && result;
    });

    return isValid;
  },

  clearAllForm: function () {
    $(Wick.Quiz.el.modalEmail + ` ${Wick.Quiz.el.input}`).val('');
  },

  disableButton: function (selector) {
    $(selector).attr('disabled', true);
  },

  enableButton: function (selector) {
    $(selector).removeAttr('disabled');
  },

  requestToEmailResult: function () {
    const userDetails = {
      email: $(Wick.Quiz.el.emailInput).val(),
      firstName: $(Wick.Quiz.el.firstNameInput).val(),
      lastName: $(Wick.Quiz.el.surnameInput).val(),
    };

    Wick.Quiz.disableButton(Wick.Quiz.el.submitBtn);

    return new Promise((resolve, reject) => {
      const payload = {
        ...userDetails
      };
      const eventDetail = {resolve, reject};
      const event = createEvent(Wick.Quiz.STYLE_QUIZ_EMAIL, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(() => {
        Wick.Quiz.closeModal(Wick.Quiz.el.modalEmail);
      })
      .catch((error) => {
        console.error(error);
      })
      .finally(() => {
        Wick.Quiz.clearAllForm();
        Wick.Quiz.showModal(Wick.Quiz.el.modalEmailFinal);
        Wick.Quiz.enableButton(Wick.Quiz.el.submitBtn);
      })
  },

  submitForm: function(event) {
    event.preventDefault();
    if (Wick.Quiz.validateForm()) {
      Wick.Quiz.requestToEmailResult();
    } else {
      $(Wick.Quiz.el.quizForm).addClass(Wick.Quiz.el.formInvalidClass);
    }
  },

  loadScript: function(src, callback) {
    const script = document.createElement("script");
    script.src = src;
    script.onload = callback;
    script.onerror = () => console.error("Failed to load script:", src);
    document.head.appendChild(script);
  },

  handleSaveAsPDF: function() {
    if (typeof html2pdf === "undefined") {
      Wick.Quiz.loadScript("https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.2/html2pdf.bundle.min.js", () => {
        Wick.Quiz.generatePDF();
      });
    } else {
      Wick.Quiz.generatePDF();
    }
  },

  convertSvgToCanvas: function(selector) {
    return new Promise((resolve, reject) => {
      const svgImages = document.querySelectorAll(selector + ' img[src*=".svg"]');
      const scale = 2;
      let pending = svgImages.length;
      if (pending === 0) resolve();

      svgImages.forEach((img) => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        const image = new Image();

        image.crossOrigin = "Anonymous";

        image.onload = () => {
          canvas.width = image.width * scale;
          canvas.height = image.height * scale;
          ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

          try {
            img.src = canvas.toDataURL("image/png");
            pending -= 1;
          } catch (error) {
            reject(error);
            return;
          }

          if (pending === 0) resolve();
        };
        image.onerror = () => {
          reject(new Error("Failed to load image"));
        };
        image.src = img.src;
      });
    });
  },

  generatePDF: function() {
    const selector = document.body.querySelector(Wick.Quiz.el.quizContainer);
    Wick.Quiz.convertSvgToCanvas(Wick.Quiz.el.quizContainer).then(() => {
      const options = {
        margin: 1,
        filename: 'Wickes Matchmaker Quiz result.pdf',
        image: {
          type: 'jpeg',
          quality: 0.98
        },
        html2canvas: {
          scale: 2,
          useCORS: true,
          windowWidth: 770
        },
        jsPDF: {
          format: [695.28, 200]
        }
      };

      html2pdf()
          .set(options)
          .from(selector)
          .output('datauristring')
          .then(function (pdfAsDataUri) {

            const postMessage = {
              event: 'matchMakertoolResultBase64',
              data: {
                filename: options.filename,
                file: pdfAsDataUri
              }
            };

            if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
              window.ReactNativeWebView.postMessage(JSON.stringify(postMessage));
            } else {
              console.warn('ReactNativeWebView not available');
            }
          }).save();
    }).catch(error => console.error("Error converting SVGs:", error));
  },

  handlePrint: function () {
    const selector = Wick.Quiz.el.html;
    let printFrame = document.createElement('iframe');
    printFrame.name = 'printFrame';
    printFrame.style.display = 'none';

    document.body.appendChild(printFrame);

    let printWindow = printFrame.contentWindow;
    printWindow.document.write('<html><head>');

    $('[type="text/css"]').each(function(i, el) {
      printWindow.document.write(el.outerHTML);
    });

    printWindow.document.write('</head><body>');

    let content = $(selector).clone();
    content.find('script, iframe').remove();

    content.find('svg').each(function() {
      this.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    });
    printWindow.document.write(content.html());
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();

    printFrame.onload = function() {
      setTimeout(function() {
        printWindow.print();
        document.body.removeChild(printFrame);
      }, 500);
    };
  },

  handlePrintOrPDFInteraction: function (event) {
    event.preventDefault();

    if (isTouchDevice()) {
      Wick.Quiz.handleSaveAsPDF();
    } else {
      Wick.Quiz.handlePrint();
    }
  },

  init: function () {
    $(Wick.Quiz.el.body).on('click', Wick.Quiz.el.btnQuizEmail, function (event) {
      event.preventDefault()
      Wick.Quiz.showModal(Wick.Quiz.el.modalEmail);
    });
    $(Wick.Quiz.el.cancelBtn).on('click', function (event) {
      Wick.Quiz.closeModal(Wick.Quiz.el.modal, event)
    });
    $(Wick.Quiz.el.body).on('submit', Wick.Quiz.el.quizForm, Wick.Quiz.submitForm);

    const debouncedHandleInteraction = _.debounce(Wick.Quiz.handlePrintOrPDFInteraction, 500);

    $(Wick.Quiz.el.btnPrintResultQuiz).on('click', function (event) {
      event.preventDefault();
      debouncedHandleInteraction(event);
    });

  }
};

$(document).ready(function () {
  Wick.Quiz.init();
});
