document.addEventListener("DOMContentLoaded", function () {
    loadParameterListWeatherVillage("2021", "15");
    $("#btn-update-list-weather-village").on("click", function () {
        var years = $("#choiceYear").val();
        var subDistrictId = $("#choiceSubDistrict").val();

        $.ajax({
            url: "/list-parameter-cuaca-desa/" + years + "/" + subDistrictId,
            method: "GET",
            dataType: "json",
            beforeSend: function () {
                NProgress.start(); // Menampilkan progress bar
            },

            success: function (response) {
                NProgress.done();
                $("#result").html(`<p>${response.message}</p>`);
                console.log(response);

                // agar refresh
                setTimeout(function () {
                    window.location.href = "/list-parameter-cuaca-desa";
                }, 1000);
            },

            error: function (xhr) {
                NProgress.done();
                $("#result").html(
                    "<p style='color:red;'>Gagal mengambil data!</p>"
                );

                // agar refresh
                setTimeout(function () {
                    window.location.href = "/list-parameter-cuaca-desa";
                }, 1000);
            },
        });
    });

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

        $("#span-year").text(yearValue);
        loadParameterListWeatherVillage(yearValue, subDistrictIdValue);
    });

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

        loadParameterListWeatherVillage(yearValue, subDistrictIdValue);
    });
});

let gridInstance;
function loadParameterListWeatherVillage($years, $subDistrictId) {
    const tableParameterListWeatherVillage = document.getElementById(
        "table-parameter-list-weather-village"
    );

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

    $.ajax({
        url:
            "/list-parameter-cuaca-desa/getDataParameterListWeatherVillage/" +
            $years +
            "/" +
            $subDistrictId,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const tableDataVillage = data[
                "listWeatherVillageBySubDistrict"
            ].map((item, index) => [
                index + 1,
                item["village"],
                `${item["year"]}, ${item["month"]}`,
                item["allsky_sfc_sw_dwn"],
                item["prectotcorr"],
                item["rh2m"],
                item["t2m"],
                item["ws2m"],
            ]);

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: tableDataVillage, // Update data
                    })
                    .forceRender(); // Paksa render ulang
            } else {
                // Jika grid belum ada, buat grid baru
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Desa atau Kelurahan",
                        "Tahun/bulan",
                        "radiasi matahari w/m2",
                        "Curah hujan (mm/day)",
                        "kelembapan (2m, %)",
                        "Suhu (2m, C)",
                        "Kecepatan Angin (2m, m/s)",
                    ],
                    data: tableDataVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 15,
                    },
                }).render(tableParameterListWeatherVillage);
            }
        },
    });
}
