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

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

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

let gridInstance;
function loadDataSubDistrict(years) {
    const tableContainerSubDistrict =
        document.getElementById("table-sub-district");
    if (tableContainerSubDistrict) {
        tableContainerSubDistrict.innerHTML = ""; // Bersihkan sebelum render
    }

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

            // Render ulang grid jika instance sudah ada, atau buat baru
            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableDataSubDistrict, // Update data
                    })
                    .forceRender(); // Paksa render ulang
            } else {
                // Jika grid belum ada, buat grid baru
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Kecamatan",
                        "Latitude",
                        "Longitude",
                        "Action",
                    ],
                    data: TableDataSubDistrict,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerSubDistrict);
            }
        },
    });
}
