let timerInterval;

$('#form-login').on('submit', function (e) {
    e.preventDefault();

    var $btn = $('#btn-login');
    var originalText = $btn.html();

    $btn.html('<i class="fa fa-spinner fa-spin"></i>  Entrando...').prop('disabled', true);

    $(this).ajaxSubmit({
        url: buildUrl('conta', 'login'),
        type: 'post',
        dataType: 'json',
        success: function (response) {
            notify(response[0], response[1]);

            if (response[0] === 'success') {
                if (response[2] === 'BB3B9D4C-0FB3-BEB2-EAD8-A86B0624498C' || response[2] === '49471395-DD2F-5C87-E229-33745983C1B3') {
                    window.location.href = buildUrl('Atendimentos/abertos');
                } else if (response[2] === 'token') {
                    $('#form-login').hide();
                    $('#form-login-token').show();
                    timerToken();
                } else {
                    window.location.href = buildUrl('home');
                }
            }
        },
        complete: function () {
            $btn.html(originalText).prop('disabled', false);
        },
        error: function () {
            notify('error', 'Erro ao efetuar o Login.');
        }
    });
});


$('#form-login-token').on('submit', function (e) {
    e.preventDefault();
    var $btn = $('#btn-token');
    var originalText = $btn.html();
    const formData = {
        Usuario: $('#Email').val(),
        Senha: $('#Senha').val()
    }

    $btn.html('<i class="fa fa-spinner fa-spin"></i>  Entrando...').prop('disabled', true);

    $(this).ajaxSubmit({
        url: buildUrl('conta', 'authorization'),
        type: 'post',
        dataType: 'json',
        data: formData,
        success: function (response) {
            notify(response[0], response[1]);

            if (response[0] === 'success') {
                clearInterval(timerInterval); /* parar o timer do token */
                $('.progress-container').addClass('d-none');

                if (response[2] === 'BB3B9D4C-0FB3-BEB2-EAD8-A86B0624498C' || response[2] === '49471395-DD2F-5C87-E229-33745983C1B3') {
                    window.location.href = buildUrl('Atendimentos/abertos');
                } else {
                    window.location.href = buildUrl('home');
                }
            } else {
                $btn.html(originalText).prop('disabled', false);
            }
        },
        error: function () {
            notify('error', 'Erro ao efetuar o Login.');
            $btn.html(originalText).prop('disabled', false);
        }
    });
});

$('#form-recuperar-senha').on('submit', function (e) {
    e.preventDefault();

    $(this).ajaxSubmit({
        url: buildUrl('conta', 'recuperar_senha'),
        type: 'post',
        dataType: 'json',
        success: function (response) {
            if (response[0] === 'success') {
                notify(response[0], 'Token de validação enviado para o seu SmartPhone.');

                $('#form-alterar-senha-token #Id').val(response[1]);
                $('#form-recuperar-senha').hide();
                $('#form-alterar-senha-token').show();
            } else {
                notify(response[0], response[1]);
            }
        }
    });
});

$('#form-alterar-senha-token').on('submit', function (e) {
    e.preventDefault();

    $(this).ajaxSubmit({
        url: buildUrl('conta', 'recuperar_alterar_senha_token'),
        type: 'post',
        dataType: 'json',
        success: function (response) {
            notify(response[0], response[1]);

            if (response[0] === 'success') {
                setTimeout(function () {
                    location.href = buildUrl('');
                }, 2000);
            }
        }
    });
});

$('#recuperar-senha').on('click', function () {

    $('#form-login').hide();
    $('#form-alterar-senha-token').hide();

    $('#form-recuperar-senha').show();
});

$('#retornar-login').on('click', function () {
    $('#form-login').show();
    $('#form-recuperar-senha').hide();
    $('#form-alterar-senha-token').hide();
});

function timerToken(){
    let tempo_expiracao = 60; 
    timerInterval = setInterval(() => {
        tempo_expiracao--;
        $("#timer-text").text(`O token expira em ${tempo_expiracao} segundos.`);
    
        const progressPercentage = (tempo_expiracao / 60) * 100;
        $("#progress-bar").css("width", `${progressPercentage}%`);
        $("#progress-bar").attr("aria-valuenow", progressPercentage);
    
        if (tempo_expiracao <= 0) {
            clearInterval(timerInterval);
            $("#timer-text").text("O token expirou. Por favor, solicite um novo.").css('color', 'red');
            $("#progress-bar").removeClass("progress-bar-animated").addClass("bg-danger");
            $("#btn-token").prop("disabled", true);

            setTimeout(() => {
                window.location.href = buildUrl('conta');
            }, 2500)
        }
    }, 1000);
}


