@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "User Administration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<p>
    @* <a asp-action="UserCreate">Create New</a> *@
</p>
<div id="app">
    <div class="row">
        <div class="col-md-12 col-lg-12">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">User List</h4>
                    <div class="col-md-12 col-lg-12">
                        <div>
                            <table class="table table-bordered table-hover table-striped no-wrap align-middle" id="userDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- MODAL -->
    <div class="modal fade" id="confirm-dialog" tabindex="-1" role="dialog" aria-labelledby="confirm-dialog-title" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirm-dialog-title">Confirmation</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" v-on:click="hideModal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div v-if="selectedModule">
                    <div class="modal-body">
                        <p>Are you sure you want to delete module {{ selectedModule.moduleName }}?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal" v-on:click="hideModal">Cancel</button>
                        <input type="hidden" id="delete-id">
                        <a id="confirmButton" href="#" class="btn btn-danger" v-on:click="confirmDelete(selectedModule)">Confirm</a>
                    </div>
                </div>
                <div v-else><p>Loading...</p></div>
            </div>
        </div>
    </div>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>

        $(function () {
            app.mount('#app');
        });

        const app = Vue.createApp({
            data() {
                return {
                    userList: null,
                    roleList: null,
                    selectedModule: null,
                    selectedRole: [],
                    userDatatable: null,
                };
            },
            mounted() {
                this.fetchUsers();
                this.fetchRoles();
            },
            methods: {
                async fetchUsers() {
                    fetch('/AdminAPI/GetUserList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        this.userList = data.userInfo.length ? data.userInfo : [];
                        this.$nextTick(() => {
                            if (this.userDatatable != null) { 
                                this.userDatatable.clear().destroy();
                            }
                            this.initiateTable();
                        });
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });
                },
                async fetchRoles() {
                    fetch('/RoleAPI/GetRoleList', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        this.roleList = data.length ? data : [];
                    })
                    .catch(error => {
                        console.error('There was a problem with the fetch operation:', error);
                    });
                },
                editUser(user) {
                    // Check if the user ID exists
                    if (module.settingId) {
                        // Redirect the user to the edit user page
                        window.location.href = 'ModuleSetting/' + module.settingId;
                    } else {
                        console.error('Module ID not found');
                    }
                },
                deleteUser(user) {
                    this.selectedModule = module; // Set selected user
                    $('#confirm-dialog').modal('show'); // Show the modal

                    // console.log(this.selectedModule);
                },
                confirmDelete(user) {
                    fetch(`/ModuleAPI/DeleteModule/${module.settingId}`, {
                        method: 'POST'
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to delete module');
                            }
                            // Remove the deleted user from the userData array
                            const index = this.moduleData.findIndex(u => u.settingId === module.settingId);
                            if (index !== -1) {
                                alert("Module deleted successfully");
                                this.moduleData.splice(index, 1);
                            }
                            this.hideModal(); // Hide the modal after deletion
                        })
                        .catch(error => {
                            console.error('Failed to delete module with status:', error);
                        });
                },
                hideModal() {
                    $('#confirm-dialog').modal('hide');
                },
                async initiateTable() {
                    self = this;
                    this.userDatatable = $('#userDatatable').DataTable({
                        "data": self.userList,
                        "columns": [
                            {
                                "title": "Email",
                                "data": "email",
                            },
                            {
                                "title": "Company Name",
                                "data": "company",
                            },
                            {
                                "title": "Department",
                                "data": "department",
                            },
                            {
                                "title": "Role",
                                "data": "role",
                                "render": function (data, type, row, meta) {
                                    if (data.length > 0) {
                                        return data;
                                    } 
                                    else if(row.company == null && row.department == null) {
                                        var thisCol = `
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <select class="form-select role-select" data-id="${row.id}" disabled>
                                                        <option value="" selected disabled>Select Role</option>
                                                        ${self.roleList && self.roleList.map(role => `<option value="${role.name}">${role.name}</option>`).join('')}
                                                    </select>
                                                </div>
                                                <div class="col-md-6">
                                                    <button type="button" class="btn btn-primary update-btn" data-id="${row.id}" disabled>Update</button>
                                                </div>
                                            </div>`
                                        return thisCol;
                                    } 
                                    else {
                                        var thisCol = `
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <select class="form-select role-select" data-id="${row.id}">
                                                        <option value="" selected disabled>Select Role</option>
                                                        ${self.roleList && self.roleList.map(role => `<option value="${role.name}">${role.name}</option>`).join('')}
                                                    </select>
                                                </div>
                                                <div class="col-md-6">
                                                    <button type="button" class="btn btn-primary update-btn" data-id="${row.id}">Update</button>
                                                </div>
                                            </div>`
                                        return thisCol;
                                    }
                                },
                            },
                            {
                                "title": "Info Status",
                                "data": "status",
                                "render": function (data, type, row, meta) {
                                    return data == 1 ? `Info Complete`: `Info Incomplete`;
                                },
                                "createdCell": function (td, cellData, rowData, row, col) {
                                    // Add text-danger or text-success class to the <td>
                                    if (cellData == 1) {
                                        $(td).addClass('text-success');
                                    } else {
                                        $(td).addClass('text-danger');
                                    }
                                },
                            },
                            {
                                "title": "User Details",
                                "data": "id",
                                "render": function (data, type, row, meta) {
                                    if (!row.role.includes("SuperAdmin") && !row.role.includes("SystemAdmin")) {
                                        var detailsButton = `<button type="button" class="btn btn-danger details-btn" data-id="${data}">Details</button>`;
                                        return detailsButton;
                                    } else {
                                        return ""; // Return empty string if role is "SuperAdmin" or "SystemAdmin"
                                    }
                                },
                            },
                            {
                                "title": "Delete",
                                "data": "id",
                                "render": function (data, type, row, meta) {
                                    if (!row.role.includes("SuperAdmin") && !row.role.includes("SystemAdmin")) {
                                        var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
                                        return deleteButton;
                                    } else {
                                        return ""; // Return empty string if role is "SuperAdmin" or "SystemAdmin"
                                    }
                                },
                            }
                        ],
                        responsive: true,
                        order: [[5, 'asc']],
                    })

                    // Attach click event listener to the button
                    $('#userDatatable tbody').on('change', '.role-select', function () {
                        const userId = $(this).data('id');
                        const role = $(this).val();
                        self.selectedRole[userId] = role;
                    });

                    // Attach click event listener to the update button
                    $('#userDatatable tbody').on('click', '.update-btn', function () {
                        const userId = $(this).data('id');
                        const thisUserRole = self.selectedRole[userId];
                        self.updateInfo(thisUserRole, userId);
                    });

                    // Attach click event listener to the delete button
                    $('#itemDatatable tbody').on('click', '.delete-btn', function () {
                        const itemId = $(this).data('id');
                        self.deleteItem(itemId);
                    });

                    this.loading = false;
                },
                async updateInfo(thisUserRole, thisUserId) {
                    try
                    {
                        const response = await fetch(`/AdminAPI/UpdateUserStatusAndRole/${thisUserId}`, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(thisUserRole)
                        });

                        if (!response.ok) {
                            throw new Error('Failed to update role');
                        }

                        console.log('Role updated successfully');
                    } 
                    catch (error) {
                        console.error('Failed to update role:', error);
                    }

                    // console.log("User ID:" + thisUserId + " Role:" + thisUserRole);

                    //How to reload the table with new data from this.userList

                    this.fetchUsers();
                },
            }
        })
    </script>
}
