$(document).ready(function() {
  $('.js-method').on('click', function() {
    var $this = $(this);
    if ($this.prop('checked')) {
      $this
        .closest('.js-verify-checked')
        .find('input[type=text]')
        .val('')
        .attr('disabled', true);
    } else {
      $this
        .closest('.js-verify-checked')
        .find('input[type=text]')
        .val('')
        .attr('disabled', false);
    }
  });

  const buttonTestConnection = document.querySelector('.js-validate-credentials');
  const validateCredentialsUrl = buttonTestConnection.dataset.url;
  let request = false;

  const credentialId = document.querySelector('input[name="mercadopago2_client_id"]');
  const credentialKey = document.querySelector('input[name="mercadopago2_client_secret"]');

  function handleAuthenticateButton() {
    if (!credentialId.value || !credentialKey.value) {
      buttonTestConnection.setAttribute('disabled', true);
    } else {
      buttonTestConnection.removeAttribute('disabled', true);
    }
  }

  handleAuthenticateButton();

  credentialId.addEventListener('change', handleAuthenticateButton);
  credentialKey.addEventListener('change', handleAuthenticateButton);

  function validateCredentials(e) {
    e.preventDefault();

    if (request) {
      return;
    }

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

    request = true;
    window
      .axiosApi({
        method: 'get',
        url: validateCredentialsUrl,
        params: { mercadopago2_client_id: credentialId.value, mercadopago2_client_secret: credentialKey.value },
      })
      .then(({ data }) => {
        notificationMsg(data.message, data.type);
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {
        this.classList.remove('btn-loading');
        this.disabled = false;
        request = false;
      });
  }

  buttonTestConnection.addEventListener('click', validateCredentials);
});
