document.addEventListener("DOMContentLoaded", function () {
    loadDataVillage("2021");

    $("#choiceYear").on("change", function () {
        year = $(this).val();

        $("#span-year").text(year);
        loadDataVillage(year);
    });
});

let gridInstance;
function loadDataVillage(year) {
    const tableContainerVillage = document.getElementById("table-village");
    if (tableContainerVillage) {
        tableContainerVillage.innerHTML = "";
    }

    $.ajax({
        url: `/parameter-desa/getDataVillage`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableDataVillage = data["allVillage"].map((item, index) => [
                index + 1,
                item["sub_district"],
                item["village"],
                item["latitude"],
                item["longitude"],
                gridjs.html(
                    `<a href="/parameter-desa/${item["latitude"]}/${item["longitude"]}/${year}" class="btn btn-excel btn-success waves-effect waves-light">Excel</a>`
                ),
            ]);

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableDataVillage, // Update data
                    })
                    .forceRender(); // Paksa render ulang
            } else {
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Kecamatan",
                        "Desa / Kelurahan",
                        "Latitude",
                        "Longitude",
                        "Action",
                    ],
                    data: TableDataVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerVillage);
            }
        },
    });
}
