document.addEventListener("DOMContentLoaded", function () {
    loadParameterListWeatherSubDistrict("2021");
    $("#btn-update-list-weather-sub-district").on("click", function () {
        var years = $("#choiceYear").val();

        // window.open("/list-parameter-cuaca-kecamatan/" + years, "_self");

        $.ajax({
            url: "/list-parameter-cuaca-kecamatan/" + years,
            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-kecamatan";
                }, 1000);
            },
            error: function (xhr) {
                NProgress.done();
                $("#result").html(
                    "<p style='color:red;'>Gagal mengambil data!</p>"
                );
                console.log("gagal");
            },
        });
    });

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

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

let gridInstance;
function loadParameterListWeatherSubDistrict(year) {
    const tableParameterListWeatherSubDistrict = document.getElementById(
        "table-parameter-list-weather-sub-district"
    );

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

    $.ajax({
        url:
            "/list-parameter-cuaca-kecamatan/getDataParameterListWeatherSubDistrict/" +
            year,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableDataSubDistrict = data["listWeatherSubDistrict"].map(
                (item, index) => [
                    index + 1,
                    item["sub_district"],
                    `${item["year"]}, ${item["month"]}`,
                    item["allsky_sfc_sw_dwn"],
                    item["prectotcorr"],
                    item["rh2m"],
                    item["t2m"],
                    item["ws2m"],
                ]
            );

            // 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",
                        "Tahun/bulan",
                        "radiasi matahari w/m2",
                        "Curah hujan (mm/day)",
                        "kelembapan (2m, %)",
                        "Suhu (2m, C)",
                        "Kecepatan Angin (2m, m/s)",
                    ],
                    data: TableDataSubDistrict,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 15,
                    },
                }).render(tableParameterListWeatherSubDistrict);
            }
        },
    });
}
