@using CarCareTracker.Helper
@{
    ViewData["Title"] = "Admin Panel";
}
@inject IConfigHelper config
@inject ITranslationHelper translator
@{
    bool emailServerIsSetup = true;
    var mailConfig = config.GetMailConfig();
    var userLanguage = config.GetServerLanguage();
    if (mailConfig is null || string.IsNullOrWhiteSpace(mailConfig.EmailServer))
    {
        emailServerIsSetup = false;
    }
}
@model AdminViewModel
<div class="container">
    <div class="row d-flex align-items-center justify-content-between justify-content-md-start">
        <div class="col-2 col-md-1">
            <a href="/Home" class="btn btn-secondary btn-md mt-1 mb-1"><i class="bi bi-arrow-left-square"></i></a>
        </div>
        <div class="col-6 col-md-7 text-end text-md-start">
            <span class="display-6">@translator.Translate(userLanguage, "Admin Panel")</span>
        </div>
    </div>
    <hr />
    <div class="row">
        <div class="col-12">
            <div class="row">
                <div class="col-2 d-flex align-items-center">
                    <span class="lead">@translator.Translate(userLanguage, "Users")</span>
                </div>
                <div class="col-10 d-flex align-items-center justify-content-end">
                    <button onclick="showTokenModal()" class="btn btn-primary btn-md mt-1 mb-1">
                        <i class="bi bi-pencil-square me-2"></i>@translator.Translate(userLanguage, "Manage Tokens")
                    </button>
                </div>
            </div>
            <hr />
            <table class="table table-hover">
                <thead class="sticky-top">
                    <tr class="d-flex">
                        <th scope="col" class="col-4">@translator.Translate(userLanguage, "Username")</th>
                        <th scope="col" class="col-4">@translator.Translate(userLanguage, "Email")</th>
                        <th scope="col" class="col-2">@translator.Translate(userLanguage, "Is Admin")</th>
                        <th scope="col" class="col-2">@translator.Translate(userLanguage, "Delete")</th>
                    </tr>
                </thead>
                <tbody id="userTable">
                    @await Html.PartialAsync("_Users", Model.Users)
                </tbody>
            </table>
        </div>
    </div>
    <div class="modal fade" data-bs-focus="false" id="tokenModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                        <div class="d-flex align-items-center">
                            <span class="lead">@translator.Translate(userLanguage, "Tokens")</span>
                        </div>
                        <div class="d-flex align-items-center ms-auto">
                            <div class="btn-group">
                                <button onclick="generateNewToken()" class="btn btn-primary btn-md mt-1 mb-1">
                                    <i class="bi bi-pencil-square me-2"></i>@translator.Translate(userLanguage, "Generate")
                                </button>
                                <button class="btn btn-outline-primary btn-md mt-1 mb-1" @(emailServerIsSetup ? "" : "disabled") onclick="toggleAutoNotify(event)">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" role="switch" id="enableAutoNotify" @(emailServerIsSetup ? "checked" : "disabled")>
                                        <label class="form-check-label" for="enableAutoNotify">@translator.Translate(userLanguage, "Notify")</label>
                                    </div>
                                </button>
                            </div>
                        <button class="btn btn-close btn-md mt-1 mb-1 ms-2" onclick="hideTokenModal()" aria-label="Close"></button>
                        </div>
                </div>
                <div class="modal-body">
                    <table class="table table-hover">
                        <thead class="sticky-top">
                            <tr class="d-flex">
                                <th scope="col" class="col-4">@translator.Translate(userLanguage, "Token")</th>
                                <th scope="col" class="col-6">@translator.Translate(userLanguage, "Issued To")</th>
                                <th scope="col" class="col-2">@translator.Translate(userLanguage, "Delete")</th>
                            </tr>
                        </thead>
                        <tbody id="tokenTable">
                            @await Html.PartialAsync("_Tokens", Model.Tokens)
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    function showTokenModal() {
        $("#tokenModal").modal('show');
    }
    function hideTokenModal() {
        $("#tokenModal").modal('hide');
    }
    function reloadTokenTable() {
        $.get('/Admin/GetTokenPartialView', function (data) {
            $("#tokenTable").html(data);
        });
    }
    function reloadUserTable() {
        $.get('/Admin/GetUserPartialView', function (data) {
            $("#userTable").html(data);
        });
    }
    function updateUserAdmin(userId, sender) {
        var isChecked = $(sender).is(":checked");
        $.post('/Admin/UpdateUserAdminStatus', { userId: userId, isAdmin: isChecked }, function (data) {
            if (data) {
                reloadUserTable();
            } else {
                errorToast(genericErrorMessage());
            }
        });
    }
    function toggleAutoNotify(e) {
        if (!$("#enableAutoNotify").attr("disabled")) {
            if ($(e.target).hasClass('btn')) {
                $("#enableAutoNotify").trigger('click');
            }
        }
    }
    function deleteToken(tokenId) {
        $.post(`/Admin/DeleteToken?tokenId=${tokenId}`, function (data) {
            if (data) {
                reloadTokenTable();
            } else {
                errorToast(genericErrorMessage());
            }
        });
    }
    function deleteUser(userId) {
        Swal.fire({
            title: "Confirm Deletion?",
            text: "Deleted Users cannot be restored.",
            showCancelButton: true,
            confirmButtonText: "Delete",
            confirmButtonColor: "#dc3545"
        }).then((result) => {
            if (result.isConfirmed) {
                $.post(`/Admin/DeleteUser?userId=${userId}`, function (data) {
                    if (data) {
                        reloadUserTable();
                    } else {
                        errorToast(genericErrorMessage());
                    }
                });
            }
        });
    }
    function generateNewToken() {
        Swal.fire({
            title: 'Generate Token',
            html: `
                                <input type="text" id="inputEmail" class="swal2-input" placeholder="Email Address" onkeydown="handleSwalEnter(event)">
                                `,
            confirmButtonText: 'Generate',
            focusConfirm: false,
            preConfirm: () => {
                const emailAddress = $("#inputEmail").val();
                if (!emailAddress) {
                    Swal.showValidationMessage(`Please enter an email address`)
                }
                return { emailAddress }
            },
        }).then(function (result) {
            if (result.isConfirmed) {
                var autoNotify = $("#enableAutoNotify").is(":checked");
                $.get('/Admin/GenerateNewToken', { emailAddress: result.value.emailAddress, autoNotify: autoNotify }, function (data) {
                    if (data.success) {
                        reloadTokenTable();
                    } else {
                        errorToast(data.message)
                    }
                });
            }
        });
    }
</script>