function refreshCardsList($list) {
    emptyError();
    var creditCard = $("input[name='creditCard']:checked").val();
    var invoiceID = $('#invoice').val();
    var userID = $('#user-card').val();

    $.get("/cardOnFiles/refreshCardsList", {
        list: $list,
        UUIDFragment: creditCard,
        invoice: invoiceID,
        userID: userID
    })
        .done(function (data) {
            var $injector = angular.element(document.body).injector();
            $injector.invoke(($rootScope, $compile) => {
                $('.' + $list).html(data);
                $compile(angular.element('.' + $list))($rootScope);
            });
        });
}

$(document).off('click', '.card-delete').on('click', '.card-delete', function (e) {
    e.preventDefault();
    var element = $(this);
    var refreshLists = jQuery.parseJSON(element.attr('data-refresh-lists'));
    swal({
        title: element.attr('data-confirm'),
        type: 'warning',
        showConfirmButton: true,
        showCancelButton: true
    }).then(function (result) {
        if (result.value) {
            $.ajax({
                url: element.attr('data-href'),
                type: 'GET',
                success: function (data) {
                    if (data.messages) {
                        $.each(data.messages, function (index, value) {
                            notify(value);
                        });
                    }
                    $.each(refreshLists, function (key, value) {
                        refreshCardsList(value);
                    });

                    if (!data.hasActiveCards) {
                        $('.charge-button').hide();
                    }
                    emptyError();
                }
            });
        }
    });

    return false;
});

$(document).off('click', '.change-subscription-payment-method').on('click', '.change-subscription-payment-method', function (e) {
    e.preventDefault();
    var element = $(this);
    var creditCard = $("input[name='creditCard']:checked").val();
    var refreshLists = jQuery.parseJSON(element.attr('data-refresh-lists'));
    if (!creditCard) {
        notify(_t('HAVE_AT_LEAST_ONE_SUBSCRIPTION_CARD'));
    } else {
        swal({
            title: element.attr('data-confirm'),
            type: 'warning',
            showConfirmButton: true,
            showCancelButton: true
        }).then(function (result) {
            if (result.value) {
                $.ajax({
                    url: element.attr('data-href'),
                    data: {
                        UUIDFragment: creditCard
                    },
                    type: 'GET',
                    success: function (data) {
                        if (data.messages) {
                            $.each(data.messages, function (index, value) {
                                notify(value);
                            });
                            $.each(refreshLists, function (key, value) {
                                refreshCardsList(value);
                            });
                            closeDialog();
                        }
                    }
                });
            }
        });
    }

    return false;
});

$(document).on('click','.submit-existing-payment-method', function(e) {
    if (typeof $('input[name="creditCard"]:checked').val() === "undefined") {
        e.preventDefault();

        swal({
            title: "Please select the payment method",
            type: 'warning',
        });
    }


});

$(document).on('click','#submit-card-validation', function(e) {
    e.preventDefault();

    $('#submit-card-validation').addClass('disabled');

    $.post($("#validate-banck-form").attr('action'), $("#validate-banck-form").serialize(), function (data) {
        $('#submit-card-validation').removeClass('disabled');

        if (!data.success) {
            displayPaymentError(data.messages[0]);
        } else {
            if (data.refreshLists) {
                var refreshLists = JSON.parse(data.refreshLists);

                $.each(refreshLists, function (key, value) {
                    refreshCardsList(value);
                });
            }

            angular.element('.modal').scope().$close();
        }
    });
});

function displayPaymentError(error) {
    $('.validate-error-container').show();
    $("#validate_error").show().html(String(error));
}


function emptyError() {
    $('#payment_error').hide();
}

/*Display Tabs*/
$(document).ready(function () {
    $('#paypal-tab').on('click', function (e) {
        e.preventDefault();
        $("input[name='creditCard']").prop('checked', false);
        $(this).tab('show');
        return false;
    });
    $('#credit-card-tab').on('click', function (e) {
        e.preventDefault();
        $("input[name='creditCard']").prop('checked', false);
        $(this).tab('show');
        return false;
    })
    $('#bank-account-tab').on('click', function (e) {
        e.preventDefault();
        $("input[name='creditCard']").prop('checked', false);
        $(this).tab('show');
        return false;
    })
    $('#balance-tab').on('click', function (e) {
        e.preventDefault();
        $("input[name='creditCard']").prop('checked', false);
        $(this).tab('show');
        return false;
    })
});

function createBankAccountUsingPlaid(userID, refreshList, redirect) {
    if (typeof redirect === "undefined") {
        redirect = "";
    }

    $.post(
        '/bankAccount/getPlaidPublicToken',
        {userID: userID},
        function (data) {
            if (data.token.length > 0) {
                var linkHandler = Plaid.create({
                    token: data.token,
                    env: data.env,
                    onSuccess: function (public_token, metadata) {
                        switch (metadata.accounts.length) {
                            case 0:
                                swal({
                                    title: "You don't have anny account for this bank!",
                                    type: 'error',
                                });
                                break;
                            case 1:
                                postBankAccountUsingPlaid(userID, refreshList, metadata.accounts[0].id, public_token, redirect);

                                break;
                            default:
                                swal({
                                    title: "You have multiple account for this bank!",
                                    type: 'error',
                                });
                                break;

                                console.log(metadata.accounts);
                        }


                    }
                });

                linkHandler.open();
            } else if (data.error.length > 0) {
                swal({
                    title: data.error,
                    type: 'error',
                });
            }
        },
        'json'
    );
}

function postBankAccountUsingPlaid(userID, refreshList, accountID, publicToken, redirect) {
    $.post(
        '/bankAccount/createBankAccountWithPlaid',
        {
            userID: userID,
            accountID: accountID,
            publicToken: publicToken
        },
        function (data) {
            if (data.success) {
                if (refreshList.length > 0) {
                    refreshLists = JSON.parse(decodeURI(refreshList));

                    $.each(refreshLists, function (key, value) {
                        refreshCardsList(value);
                    });
                } else if (typeof redirect !== "undefined" && redirect.length > 0) {
                    window.location.href = redirect;
                }
            } else {
                swal({
                    title: data.messages[0],
                    type: 'error',
                });
            }
        },
        'json'
    );
}

function closeCurrentModal() {
    angular.element('.modal').scope().$close();
}