import documentReady from '@assets/js/documentReady';
import axiosApi from '@assets/js/axios-api.js';
import TextWithVar from '@assets/js/valid-text-with-vars';

documentReady(init);

function init() {
  let editor;

  const textarea = document.getElementById('conteudo_layout');
  const positions = {
    start: textarea.value.length,
    end: textarea.value.length,
  };
  const useCkeditor = textarea.dataset.ckeditor;
  const variablesButtons = document.querySelectorAll('.js-variables');
  const fieldMaxlength = document.querySelector('.js-field-maxlength');

  initEditor();

  if (window.testEmailActive) {
    initEmailTest();
  }

  function initEditor() {
    function countCharacters() {
      let caracteresRestantes = textarea.maxLength;
      let caracteresDigitados = textarea.value.length;
      caracteresRestantes = caracteresRestantes - caracteresDigitados;
      if (fieldMaxlength) {
        fieldMaxlength.innerHTML = 'Caracteres restantes: ' + caracteresRestantes;
      }
    }

    function setPosition() {
      positions.start = textarea.selectionStart;
      positions.end = textarea.selectionEnd;
    }

    countCharacters();

    if (useCkeditor) {
      editor = window.CKEDITOR.replace('conteudo_layout');

      variablesButtons.forEach(variablesButtonsItem => {
        variablesButtonsItem.addEventListener('click', () => {
          const variable = window.CKEDITOR.dom.element.createFromHtml(`<span contenteditable="false">{{ ${variablesButtonsItem.dataset.variableName} }}</span>`);
          editor.insertElement(variable);
        });
      });
    } else {
      new TextWithVar(textarea);

      textarea.addEventListener('click', () => setPosition(positions));
      textarea.addEventListener('keyup', () => setPosition(positions));
      textarea.addEventListener('input', countCharacters);

      variablesButtons.forEach(variablesButtonsItem => {
        variablesButtonsItem.addEventListener('click', () => {
          const value = textarea.value;
          const variable = `{{ ${variablesButtonsItem.dataset.variableName} }}`;
          const textBeforeVariable = value.slice(0, positions.start);
          const textAfterVariable = value.slice(positions.end, value.length);

          const conteudo_layout = textBeforeVariable + variable + textAfterVariable;

          const maxLength = textarea.getAttribute('maxLength');

          if (!maxLength || conteudo_layout.length <= maxLength) {
            const varEnd = positions.end + variable.length;
            textarea.value = conteudo_layout;
            textarea.setSelectionRange(varEnd, varEnd);
          }
          textarea.focus();
          setPosition(positions);
        });
      });
    }
  }

  function initEmailTest() {
    const tags = [];
    const tagContainer = document.querySelector('.js-tag-container');
    const input = tagContainer.querySelector('input');
    const sendEmailsButton = document.querySelector('.js-email-test');

    input.addEventListener('keyup', addTags);
    sendEmailsButton.addEventListener('click', handleSendEmails);

    function addTags(event) {
      event.preventDefault();
      event.stopPropagation();

      const keyPressedIsEnter = event.key === 'Enter';
      const keyPressedIsComma = event.key === ';';
      const keyPressedIsBackspace = event.key === 'Backspace';
      const keyPressedIsSpace = event.key === ' ';

      if (input.value === '' && keyPressedIsBackspace && tags.length) {
        const lastAddedTag = tags[tags.length - 1];
        tags.pop();
        input.value = lastAddedTag;
        updateTags();
      }

      input.classList.remove('text-error');

      if ((input.value > '' && keyPressedIsComma) || keyPressedIsEnter || keyPressedIsSpace) {
        let tag = keyPressedIsComma ? input.value.split(';')[0] : input.value;
        tag = tag.trim();
        const isValidEmail = validateEmail(tag);

        if (isValidEmail) {
          tags.push(tag);
          updateTags();
          input.value = '';
        } else {
          input.classList.add('text-error');
        }
      }
    }

    function updateTags() {
      clearTags();

      tags
        .slice()
        .reverse()
        .forEach(tag => {
          tagContainer.prepend(createTag(tag));
        });
    }

    function validateEmail(email) {
      const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return regex.test(String(email).toLowerCase());
    }

    function createTag(tag) {
      const div = document.createElement('div');
      div.classList.add('js-tag', 'bottom-margin-x-small');

      const content = document.createElement('span');
      content.classList.add(
        'visible-inline-block',
        'border-gray',
        'background-gray',
        'rounded-x-small',
        'left-padding-x-small'
      );
      content.style.maxWidth = '100%';
      content.style.whiteSpace = 'nowrap';
      div.append(content);

      const span = document.createElement('span');
      span.classList.add('visible-inline-block', 'vertical-middle', 'text-ellipsis');
      span.style.maxWidth = 'calc(100% - 25px)';
      span.textContent = tag;
      span.title = tag;
      content.append(span);

      const i = document.createElement('i');
      i.classList.add(
        'fas',
        'fa-times',
        'text-small',
        'text-gray',
        'vertical-middle',
        'vertical-padding-x-small',
        'horizontal-padding-small',
        'cursor-pointer'
      );
      i.onclick = removeTag;
      i.setAttribute('data-id', tag);
      content.append(i);

      return div;
    }

    function removeTag(event) {
      const buttonClose = event.currentTarget;
      const id = buttonClose.dataset.id;
      const index = tags.indexOf(id);
      tags.splice(index, 1);

      updateTags();
    }

    function clearTags() {
      tagContainer.querySelectorAll('.js-tag').forEach(tagElement => tagElement.remove());
    }

    function handleSendEmails(event) {
      event.preventDefault();

      let emails = tags.join(';');
      if (!tags.length && input.value > '') {
        const isValidEmail = validateEmail(input.value);

        if (isValidEmail) {
          emails = input.value.trim();
        }
      }

      if (!emails) {
        return;
      }
      emails = emails + ';';

      sendEmails(emails);
    }

    function sendEmails(emails) {
      const containerFeedback = document.querySelector('.js-feedback-message');
      const typeEmail = document.getElementById('tipo_layout').value;
      const token = document.body.dataset.token;
      const contentLayout = encodeURIComponent(useCkeditor ? editor.getData() : textarea.value);

      const url = 'index.php?route=design/layout_personalizado/emailTeste&token=' + token;
      const data = `email_teste=${emails}&tipo_email=${typeEmail}&conteudo_layout=${contentLayout}`;

      sendEmailsButton.classList.add('btn-loading');
      sendEmailsButton.disabled = true;

      function createMessage(message, type) {
        const div = document.createElement('div');
        div.classList.add(
          `background-${type}`,
          `text-${type}`,
          `border-${type}`,
          'rounded-x-small',
          'text-small',
          'padding-small',
          'top-margin-small',
          'cursor-pointer'
        );
        div.textContent = message;
        div.addEventListener('click', () => {
          div.remove();
        });
        containerFeedback.append(div);
      }

      axiosApi({
        method: 'post',
        url,
        data,
      })
        .then(({ data }) => {
          const { success, error } = data;
          containerFeedback.innerHTML = '';

          if (success) {
            createMessage(success, 'success');
          }

          if (error) {
            const { email_teste, warning } = error;
            if (email_teste) {
              createMessage(email_teste, 'error');
            }
            if (warning) {
              createMessage(warning, 'error');
            }
          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          sendEmailsButton.classList.remove('btn-loading');
          sendEmailsButton.disabled = false;
        });
    }
  }
}
