(function ( $ ) {
    'use strict';

	const AccountStatus = {
		'active': 'active',
		'in_deletion': 'in_deletion',
	}

    // Render the account list into your hidden container
	function renderAccountList(accounts) {
		var $wrapper = $('#verfacto-account-selection');
		var $ul      = $('#verfacto-accounts-list').empty();

		if ( ! accounts.length ) {
			$ul.append(
				$('<li/>', {
					text: 'No active account for this user',
					class: 'no-accounts-message'
				})
			);
		} else {
			accounts.forEach(function(acc) {
				var isDeleting = acc.status === AccountStatus.in_deletion;

				var $nameCell = $('<span/>').text(acc.display_name);
				var $actionCell = $('<div/>', { class: 'verfacto-account-action' });

				if ( isDeleting ) {
					$actionCell.append(
						$('<span/>', {
							class: 'verfacto-badge in-deletion',
							text: 'in deletion'
						})
					);
				}

				var btnText = isDeleting ? 'Re-integrate' : 'Connect';
				var $btn = $('<button/>', {
					type: 'button',
					class: 'verfacto-connect-account verfacto-button verfacto-button--black',
					'data-id': acc.id
				})
				.append('<span class="button-text">' + btnText + '</span>')
				.append(`
					<span class="button-loader">
					  <span></span><span></span><span></span>
					</span>
				`);

				$actionCell.append($btn);

				$ul.append(
					$('<li/>').append( $nameCell, $actionCell )
				);
			});
		}

		$wrapper.show();
	}

    // Handle Integrate form submits (step 1)
    $('#verfacto-integrate-form').on('submit', function (e) {
        e.preventDefault();
        $('.verfacto-error-message.verfacto-error-danger.ajax').hide();

        var $btn = $('#submit_integration_form');
  		$btn.addClass('loading').prop('disabled', true);

        var form      = $(this),
            form_data = new FormData(form[0]);

        form_data.append("action", "activate_verfacto");
        form_data.append("vf_nonce", verfacto_ajax.vf_nonce);

        $.ajax({
            type:        "POST",
            url:         verfacto_ajax.admin_ajax,
            contentType: false,
            processData: false,
            dataType:    'JSON',
            data:        form_data,
            cache:       false
        })
        .done(function (res) {
            $btn.removeClass('loading').prop('disabled', false);

            if (res.success) {
                // Hide login form and show account picker
                $('#verfacto-form--step1').hide();
				$('#verfacto-page-title h4').text('Connect this store');
                renderAccountList(res.data);
            } else {
                show_error_message(res.data || res.message);
            }
        })
        .fail(function (jqXHR) {
            $btn.removeClass('loading').prop('disabled', false);

            if (jqXHR.responseText === 'internal-server-error') {
                show_error_message("Something unexpected happened, please try again");
            } else if (jqXHR.responseJSON && !jqXHR.responseJSON.success) {
                show_error_message(jqXHR.responseJSON.data || jqXHR.responseJSON.message);
            } else {
                show_error_message('Some issue with API service, please try again later');
            }
        });
    });

    // Handle Connect button clicks (step 2)
    $(document).on('click', '.verfacto-connect-account', function() {
        var $btn      = $(this),
            accountId = $btn.data('id');

        $('.verfacto-error-message.verfacto-error-danger.ajax').hide();
        $btn.addClass('loading').prop('disabled', true);

		var fd = new FormData();
		fd.append("action", "verfacto_start_wc_auth");
		fd.append("vf_nonce", verfacto_ajax.vf_nonce);
		fd.append("account_id", accountId);

		$.ajax({
			type:        "POST",
			url:         verfacto_ajax.admin_ajax,
			contentType: false,
			processData: false,
			dataType:    'JSON',
			data:        fd,
			cache:       false
		})
        .done(function(res) {
            $btn.removeClass('loading').prop('disabled', false);

            if (res.url) {
                window.open(res.url, res.open_in || '_self');
            }
        })
        .fail(function() {
            $btn.removeClass('loading').prop('disabled', false);

            show_error_message('Could not start OAuth flow, please try again.');
            $btn.prop('disabled', false).text('Connect');
        });
    });

	// Close button hides the error immediately
	$(document).on('click', '.verfacto-error-close', function(){
		$(this).closest('.verfacto-error-message').hide();
	});

	function show_error_message(message_text) {
		var $error = $('.verfacto-error-message.verfacto-error-danger.ajax');
		$error.find('.verfacto-error-text').html(message_text);
		$error.show();
	}

})( jQuery );
