document.addEventListener("DOMContentLoaded", function () {
    loadListVillage("15");

    $(document).on("change", "#choiceSubDistrict", function (event) {
        let subDistrictId = $(this).val();
        loadListVillage(subDistrictId);
    });

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

        let id = $(this).data("id");
        let sub_district_id = button.getAttribute("data-sub-district-id");
        let sub_district = button.getAttribute("data-sub-district");
        let village = button.getAttribute("data-village");
        let latitude = button.getAttribute("data-latitude");
        let longitude = button.getAttribute("data-longitude");

        $('[name="villageId"]').val(id);
        $('[name="subDistrictId"]').val(sub_district_id);
        $('[name="subDistrict"]').val(sub_district).prop("disabled", true);
        $('[name="village"]').val(village);
        $('[name="latitude"]').val(latitude);
        $('[name="longitude"').val(longitude);
    });

    $(document).on("click", "#btn-hapus", function () {
        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 desa / kelurahan ?</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-data-desa/deleteVillage/" + id;
            }
        });
    });
});

let gridInstance;
function loadListVillage(subDistrictId) {
    const tableContainerListVillage =
        document.getElementById("table-list-village");

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

    $.ajax({
        url: `/list-data-desa/getListVillage` + "/" + subDistrictId,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const tableDataVillage = data["listVillage"].map((item, index) => [
                index + 1,
                item["village"],
                parseFloat(item["latitude"]).toFixed(5),
                parseFloat(item["longitude"]).toFixed(5),
                gridjs.html(
                    `<button type="button" class="btn btn-warning btn-edit-village" data-bs-toggle="modal" data-bs-target="#btn-edit"
                        data-id="${item["id"]}" data-sub-district-id="${item["sub_district_id"]}" = data-village="${item["village"]}" data-latitude="${item["latitude"]}" data-longitude="${item["longitude"]}" data-sub-district="${item["sub_district"]}">
                            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: tableDataVillage,
                    })
                    .forceRender();
            } else {
                const isMobile = window.innerWidth < 768;

                const columns = isMobile
                    ? ["No", "Desa", "Latitude", "longitude", "Aksi"]
                    : [
                          { name: "No", width: "10%" },
                          { name: "Desa", width: "30%" },
                          { name: "Latitude", width: "20%" },
                          { name: "longitude", width: "20%" },
                          { name: "Aksi", width: "20%" },
                      ];

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