/* globals _, wp, mepr_feature_plugin_data */
jQuery(function($) {
  $('.mepr-feature-plugin').on('click', function(event) {
    event.preventDefault();

    var button = $(this);
    var action = button.data('action');
    var slug = button.data('slug');
    var name = button.data('name');
    var plugin = button.data('plugin');
    var redirect = button.data('redirect');

    button.prop('disabled', true);

    var displayNotice = function(message = '', type = 'success') {
      var notice = button.closest('.mepr-sister-plugin-step-detail').find('.mepr-feature-plugin-notice');

      notice.find('p').html(message);
      notice.removeClass('notice-success notice-error');
      notice.addClass('notice-' + type)
      notice.show();

      button.prop('disabled', false);
    };

    var activate = function() {
      return wp.updates.activatePlugin({
        slug,
        name,
        plugin,
        success: function() {
          var message = action === 'install'
            ? mepr_feature_plugin_data.install_success
            : mepr_feature_plugin_data.activate_success;

          displayNotice(message);
          button.remove();

          if (redirect && redirect.length > 0) {
            setTimeout(function() {
              window.location.href = redirect;
            }, 500);
          }
        },
        error: function(response) {
          var message = mepr_feature_plugin_data.activate_error;
          message += '<br />' + _.escape(response.errorMessage);
          displayNotice(message, 'error');
        },
      });
    };

    if (action === 'install') {
      wp.updates.installPlugin({
        slug,
        error: function(response) {
          var message = mepr_feature_plugin_data.install_error;
          message += '<br />' + _.escape(response.errorMessage);
          displayNotice(message, 'error');
        },
      }).done(function() {
        activate()
      });
    } else if (action === 'activate') {
      activate();
    }
  });
});
