(function ($) {
    'use strict';

    var config = window.gfUninstallFeedback || {};
    var pluginBasename = config.plugin_basename || '';
    var pluginSlug = config.plugin_slug || 'griffinforms-form-builder';
    var pluginRow = null;
    var deactivateLink = null;

    var dialog = $('#griffinforms-uninstall-feedback-dialog');
    var reasonField = $('#griffinforms-uninstall-reason');
    var detailsField = $('#griffinforms-uninstall-details');
    var contactField = $('#griffinforms-uninstall-contact');
    var errorNotice = $('#griffinforms-uninstall-feedback-error');
    var contactEmail = $('#griffinforms-uninstall-contact-email');
    var deactivateUrl = '';

    function resetForm() {
        reasonField.val('');
        detailsField.val('');
        contactField.prop('checked', false);
        errorNotice.hide();
        contactEmail.hide();
    }

    function getAjaxUrl() {
        if (config.ajax_url) {
            return config.ajax_url;
        }
        if (typeof ajaxurl !== 'undefined') {
            return ajaxurl;
        }
        return '';
    }

    function setDialogBusy(isBusy) {
        var buttons = dialog.dialog('option', 'buttons');
        if (!buttons || !buttons.length) {
            return;
        }
        buttons.forEach(function (button) {
            if (button && button.text && button.text === config.i18n.sending) {
                return;
            }
        });
        dialog.parent().find('.ui-dialog-buttonpane button').prop('disabled', isBusy);
    }

    function submitFeedback() {
        var reason = reasonField.val();
        if (!reason) {
            errorNotice.show();
            return;
        }

        var ajaxUrl = getAjaxUrl();
        if (!ajaxUrl) {
            window.location = deactivateUrl;
            return;
        }

        setDialogBusy(true);

        $.post(ajaxUrl, {
            action: 'griffinforms_uninstall_feedback',
            nonce: config.nonce || '',
            reason: reason,
            details: detailsField.val(),
            allow_contact: contactField.is(':checked') ? 1 : 0
        })
            .always(function () {
                window.location = deactivateUrl;
            });
    }

    function ensureDialogExists() {
        if (dialog.length) {
            return;
        }
        if (config.modal_html) {
            $('body').append(config.modal_html);
            dialog = $('#griffinforms-uninstall-feedback-dialog');
            refreshFields();
        }
    }

    function refreshFields() {
        dialog = $('#griffinforms-uninstall-feedback-dialog');
        reasonField = $('#griffinforms-uninstall-reason');
        detailsField = $('#griffinforms-uninstall-details');
        contactField = $('#griffinforms-uninstall-contact');
        errorNotice = $('#griffinforms-uninstall-feedback-error');
        contactEmail = $('#griffinforms-uninstall-contact-email');
    }

    function canOpenDialog() {
        ensureDialogExists();
        refreshFields();
        return dialog.length && $.ui && $.ui.dialog;
    }

    function initDialogIfNeeded() {
        ensureDialogExists();
        refreshFields();
        if (!dialog.length || !$.ui || !$.ui.dialog) {
            return false;
        }
        if (dialog.data('ui-dialog')) {
            return true;
        }
        dialog.dialog({
            dialogClass: 'wp-dialog',
            modal: true,
            autoOpen: false,
            width: 520,
            buttons: [
                {
                    text: config.i18n.deactivate || 'Deactivate',
                    class: 'button button-primary',
                    click: function () {
                        submitFeedback();
                    }
                },
                {
                    text: config.i18n.skip_deactivate || 'Skip & Deactivate',
                    class: 'button',
                    click: function () {
                        window.location = deactivateUrl;
                    }
                },
                {
                    text: config.i18n.cancel || 'Cancel',
                    class: 'button',
                    click: function () {
                        $(this).dialog('close');
                    }
                }
            ],
            open: function () {
                resetForm();
                setDialogBusy(false);
            }
        });
        if (contactField.length) {
            contactField.on('change', function () {
                if (contactField.is(':checked')) {
                    contactEmail.show();
                } else {
                    contactEmail.hide();
                }
            });
        }
        return true;
    }

    function isDeactivateLink(href) {
        if (!href) {
            return false;
        }
        if (href.indexOf('action=deactivate') === -1) {
            return false;
        }
        if (pluginBasename) {
            if (href.indexOf('plugin=' + encodeURIComponent(pluginBasename)) !== -1) {
                return true;
            }
            if (href.indexOf(encodeURIComponent(pluginBasename)) !== -1) {
                return true;
            }
        }
        return false;
    }

    function handleDeactivateClick(event, link) {
        deactivateUrl = $(link).attr('href');
        if (!initDialogIfNeeded()) {
            return;
        }
        event.preventDefault();
        dialog.dialog('open');
    }

    function bindRowLink() {
        if (pluginBasename) {
            pluginRow = $('tr[data-plugin="' + pluginBasename + '"]');
        }
        if (!pluginRow || !pluginRow.length) {
            pluginRow = $('tr[data-slug="' + pluginSlug + '"]');
        }
        if (!pluginRow || !pluginRow.length) {
            return;
        }
        deactivateLink = pluginRow.find('.deactivate a');
        if (deactivateLink && deactivateLink.length) {
            deactivateLink.on('click', function (event) {
                handleDeactivateClick(event, this);
            });
        }
    }

    bindRowLink();

    $(document).on('click', 'a', function (event) {
        var href = $(this).attr('href');
        if (isDeactivateLink(href)) {
            handleDeactivateClick(event, this);
        }
    });
})(jQuery);
