document.addEventListener("DOMContentLoaded", function () {
    loadListUserData();

    $(document).on("click", ".btn-edit-user", function (event) {
        let button = event.target;

        let id = $(this).data("id");
        let name = button.getAttribute("data-name");
        let username = button.getAttribute("data-username");
        let jenis_kelamin = button.getAttribute("data-jenis-kelamin");
        let status = button.getAttribute("data-status");

        $('[name="user_id"]').val(id);
        $('[name="name"]').val(name).prop("readonly", true);
        $('[name="username"]').val(username).prop("readonly", true);
        $('select[name="jenis_kelamin"]')
            .val(jenis_kelamin)
            .prop("disabled", true);
        $('select[name="status_user"]').val(status);
    });

    $(document).on("click", "#btn-hapus", function (event) {
        let id = $(this).data("id");

        Swal.fire({
            html: '<div class="mt-3"><lord-icon src="https://cdn.lordicon.com/gsqxdxog.json" trigger="loop" colors="primary:#f7b84b,secondary:#f06548" style="width:100px;height:100px"></lord-icon><div class="mt-4 pt-2 fs-15 mx-5"><h4>Apakah anda benar ?</h4><p class="text-muted mx-4 mb-0">Anda benar, akan menghapus data user ?</p></div></div>',
            showCancelButton: !0,
            confirmButtonClass: "btn btn-primary w-xs me-2 mb-1",
            confirmButtonText: "Ya, hapus!",
            cancelButtonClass: "btn btn-danger w-xs mb-1",
            buttonsStyling: !1,
            showCloseButton: !0,
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = "/list-user/deleteUser/" + id;
            }
        });
    });
});

let gridInstance;
function loadListUserData() {
    const tableContainerListUserData =
        document.getElementById("table-list-user");

    if (tableContainerListUserData) {
        tableContainerListUserData.innerHTML = "";
    }

    $.ajax({
        url: `/list-user/getListUserData`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const tableDataListUser = data["listUserData"].map(
                (item, index) => [
                    index + 1,
                    item["name"],
                    item["email"],
                    item["username"],
                    item["jenis_kelamin"],
                    item["status"],
                    gridjs.html(
                        `<button type="button" class="btn btn-warning btn-edit-user" data-bs-toggle="modal" data-bs-target="#btn-edit" data-id="${item["id"]}"
                        data-name="${item["name"]}" data-email="${item["email"]}" data-username="${item["username"]}" data-jenis-kelamin="${item["jenis_kelamin"]}" data-status="${item["status"]}">
                            ubah
                        </button>
                        <button type="button" class="btn btn-danger btn-md" data-id="${item["id"]}" id="btn-hapus">hapus</button>`
                    ),
                ]
            );

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: tableDataListUser,
                    })
                    .forceRender();
            } else {
                const isMobile = window.innerWidth < 768;

                const columns = isMobile
                    ? [
                          "No",
                          "Nama",
                          "Email",
                          "Username",
                          "Jenis Kelamin",
                          "Status",
                          "Aksi",
                      ]
                    : [
                          { name: "No", width: "10%" },
                          { name: "Nama", width: "30%" },
                          { name: "Email", width: "30%" },
                          { name: "Username", width: "30%" },
                          { name: "Jenis Kelamin", width: "20%" },
                          { name: "Status", width: "20%" },
                          { name: "Aksi", width: "20%" },
                      ];

                gridInstance = new gridjs.Grid({
                    columns: columns,
                    data: tableDataListUser,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerListUserData);
            }
        },
    });
}
