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

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

        loadMapsResultPreference(years);
        loadTableResultSubDistrict(years);
    });
});

// ----------------- start geojson -------------------
// nama kumpulan file geojson per desa
const geoJSONDirectories = {
    AMaesan: [
        "Secolor.js",
        "PujerBaru.js",
        "TanahWulan.js",
        "Maesan.js",
        "Gambangan.js",
        "Suger.js",
        "SumberPakem.js",
        "SumberSari.js",
        "SumberAnyar.js",
        "Penanggungan.js",
        "Pakuniran.js",
        "GunungSari.js",
    ],
    BTamanan: [
        "Kalianyar.js",
        "KarangMelok.js",
        "Kemirian.js",
        "Mengen.js",
        "Sukosari.js",
        "SumberAnom.js",
        "SumberKemuning.js",
        "Tamanan.js",
        "Wonosuko.js",
    ],
    CTlogosari: [
        "BrambangDarussalam.js",
        "Gunosari.js",
        "JebungKidul.js",
        "JebungLor.js",
        "Kembang.js",
        "Pakisan.js",
        "Patemon.js",
        "Sulek.js",
        "Tlogosari.js",
        "Trotosari.js",
    ],
    DSukosari: ["Kerang.js", "Nogosari.js", "Pecalongan.js", "SukosariLor.js"],
    EPujer: [
        "AlasSumur.js",
        "Kejayan.js",
        "Mangli.js",
        "MaskuningKulon.js",
        "MaskuningWetan.js",
        "Mengok.js",
        "Padasan.js",
        "RanduCangkring.js",
        "Sukodono.js",
        "Sukokerto.js",
        "Sukowono.js",
    ],
    FGrujugan: [
        "Dadapan.js",
        "Dawuhan.js",
        "GrujuganKidul.js",
        "Kabuaran.js",
        "Kejawan.js",
        "Pekauman.js",
        "SumberPandan.js",
        "Taman.js",
        "TegalMijin.js",
        "Wanisodo.js",
        "Wonosari.js",
    ],
    GCurahdami: [
        "Curahdami.js",
        "Curahpoh.js",
        "Jetis.js",
        "Kupang.js",
        "Locare.js",
        "Pakuwesi.js",
        "Panambangan.js",
        "Petung.js",
        "Poncogati.js",
        "Selolembu.js",
        "SumberSalak.js",
        "Sumbersuko.js",
    ],
    HTenggarang: [
        "Bataan.js",
        "DawuhanTGR.js",
        "Gebang.js",
        "Kajar.js",
        "Kesemek.js",
        "KoncerDarulAman.js",
        "KoncerKidul.js",
        "Lojajar.js",
        "Pekalangan.js",
        "SumberSalam.js",
        "TangsilKulon.js",
        "Tenggarang.js",
    ],
    IWonosari: [
        "BendoArum.js",
        "Jumpong.js",
        "Kapuran.js",
        "LombokKulon.js",
        "LombokWetan.js",
        "PasarRejo.js",
        "Pelalangan.js",
        "SumberKalong.js",
        "TangsilWetan.js",
        "Traktakan.js",
        "Tumpeng.js",
        "WonosariWN.js",
    ],
    JTapen: [
        "Cindogo.js",
        "GunungAnyar.js",
        "JurangSapi.js",
        "KaliTapen.js",
        "MangliWetan.js",
        "Mrawan.js",
        "Taal.js",
        "Tapen.js",
        "Wonokusumo.js",
    ],
    KBondowoso: [
        "Badean.js",
        "Blindungan.js",
        "Dabasah.js",
        "Kademangan.js",
        "KembangBWS.js",
        "Kotakulon.js",
        "Nangkaan.js",
        "Pancoran.js",
        "Pejaten.js",
        "Sukowiryo.js",
        "Tamansari.js",
    ],
    LWringin: [
        "Ambulu.js",
        "Ampelan.js",
        "BanyuPutih.js",
        "BanyuWulu.js",
        "Bukor.js",
        "Glingseran.js",
        "Gubrih.js",
        "JambeWungu.js",
        "JatiSari.js",
        "JatiTamban.js",
        "SumberCanting.js",
        "SumberMalang.js",
        "Wringin.js",
    ],
    MTegalampel: [
        "KarangAnyar.js",
        "Klabang.js",
        "KlabangAgung.js",
        "Mandiro.js",
        "Purnama.js",
        "SekarPutih.js",
        "TanggulAngin.js",
        "Tegalampel.js",
    ],
    NKlabang: [
        "Besuk.js",
        "Blimbing.js",
        "KarangAnyarKL.js",
        "KarangSengon.js",
        "KlabangKL.js",
        "Klampokan.js",
        "Leprak.js",
        "Pandak.js",
        "SumberSuko.js",
        "Wonoboyo.js",
        "Wonokerto.js",
    ],
    OCermee: [
        "Bajuran.js",
        "BatuAmpar.js",
        "BatuSalang.js",
        "Bercak.js",
        "BercakAsri.js",
        "Cermee.js",
        "Grujugan.js",
        "JirekMas.js",
        "Kladi.js",
        "Palalangan.js",
        "RambanKulon.js",
        "RambanWetan.js",
        "Solor.js",
        "SulingKulon.js",
        "SulingWetan.js",
    ],
    PPrajekan: [
        "Bandilan.js",
        "Cangkring.js",
        "PrajekanKidul.js",
        "PrajekanLor.js",
        "Sempol.js",
        "Tarum.js",
        "Walidono.js",
    ],
    QPakem: [
        "AndungSari.js",
        "ArdiSaeng.js",
        "GadingSari.js",
        "KupangPK.js",
        "Pakem.js",
        "PatemonPK.js",
        "PetungPK.js",
        "SumberDumpyong.js",
    ],
    RSumberWringin: [
        "RejoAgung.js",
        "Sukorejo.js",
        "SukorejoKidul.js",
        "SumberGading.js",
        "SumberWringin.js",
        "TegalJati.js",
    ],
    SSempol: [
        "Jampit.js",
        "KaliAnyarSPL.js",
        "KaliGedang.js",
        "KalisatSPL.js",
        "SempolSPL.js",
        "SumberRejo.js",
    ],
    TBinakal: [
        "Baratan.js",
        "Bendelan.js",
        "Binakal.js",
        "GadingSariBKL.js",
        "JerukSokSok.js",
        "Kembangan.js",
        "SumberTengah.js",
        "SumberWaru.js",
    ],
    UTamanKrocok: [
        "Gentong.js",
        "Kemuningan.js",
        "Kretek.js",
        "Paguan.js",
        "SumberKokap.js",
        "TamanTMK.js",
        "Trebungan.js",
    ],
    VBotoLinggo: [
        "BotoLinggo.js",
        "Gayam.js",
        "GayamLor.js",
        "Klekehan.js",
        "Lanas.js",
        "Lumutan.js",
        "Penang.js",
        "SumberCantingBTL.js",
    ],
    WJambesari: [
        "GrujuganLorJMB.js",
        "JambeAnom.js",
        "Jambesari.js",
        "Pejagan.js",
        "Pengarang.js",
        "PucangAnom.js",
        "SumberAnyarJMB.js",
        "SumberJeruk.js",
        "TegalPasir.js",
    ],
};

// ambil file geojson
function loadGeoJSONFiles(directory, callback) {
    const files = geoJSONDirectories[directory];
    const promises = files.map((file) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement("script");
            script.src = `assets/js/custom/geojsonBondowoso/${directory}/${file}`;
            script.onload = () => {
                resolve();
            };
            script.onerror = () => reject(new Error(`Failed to load ${file}`));
            document.body.appendChild(script);
        });
    });

    // Tunggu semua file selesai dimuat
    Promise.all(promises)
        .then(callback)
        .catch((error) => {
            console.error(error.message);
        });
}

// Objek untuk menyimpan data GeoJSON setelah file dimuat
let geoJSONData = {
    "Kec Maesan": [],
    "Kec Tamanan": [],
    "Kec Tlogosari": [],
    "Kec Sukosari": [],
    "Kec Pujer": [],
    "Kec Grujugan": [],
    "Kec Curahdami": [],
    "Kec Tenggarang": [],
    "Kec Wonosari": [],
    "Kec Tapen": [],
    "Kec Bondowoso": [],
    "Kec Wringin": [],
    "Kec Tegalampel": [],
    "Kec Klabang": [],
    "Kec Cermee": [],
    "Kec Prajekan": [],
    "Kec Pakem": [],
    "Kec SumberWringin": [],
    "Kec Sempol": [],
    "Kec Binakal": [],
    "Kec Taman Krocok": [],
    "Kec Botolinggo": [],
    "Kec Jambesari": [],
};

// Kec. Maesan
loadGeoJSONFiles("AMaesan", () => {
    if (geoJSONData["Kec Maesan"]) {
        geoJSONData["Kec Maesan"] = [
            Gambangan,
            GunungSari,
            Maesan,
            Pakuniran,
            Penanggungan,
            PujerBaru,
            Secolor,
            Suger,
            SumberAnyar,
            SumberPakem,
            SumberSari,
            TanahWulan,
        ];
    }
});

// Kec. Tamanan
loadGeoJSONFiles("BTamanan", () => {
    if (geoJSONData["Kec Tamanan"]) {
        geoJSONData["Kec Tamanan"] = [
            Kalianyar,
            KarangMelok,
            Kemirian,
            Mengen,
            Sukosari,
            SumberAnom,
            SumberKemuning,
            Tamanan,
            Wonosuko,
        ];
    }
});

// Kec. Tlogosari
loadGeoJSONFiles("CTlogosari", () => {
    if (geoJSONData["Kec Tlogosari"]) {
        geoJSONData["Kec Tlogosari"] = [
            BrambangDarussalam,
            Gunosari,
            JebungKidul,
            JebungLor,
            Kembang,
            Pakisan,
            Patemon,
            Sulek,
            Tlogosari,
            Trotosari,
        ];
    }
});

// Kec. Sukosari
loadGeoJSONFiles("DSukosari", () => {
    if (geoJSONData["Kec Sukosari"]) {
        geoJSONData["Kec Sukosari"] = [
            Kerang,
            Nogosari,
            Pecalongan,
            SukosariLor,
        ];
    }
});

// Kec. Pujer
loadGeoJSONFiles("EPujer", () => {
    if (geoJSONData["Kec Pujer"]) {
        geoJSONData["Kec Pujer"] = [
            AlasSumur,
            Kejayan,
            Mangli,
            MaskuningKulon,
            MaskuningWetan,
            Mengok,
            Padasan,
            RanduCangkring,
            Sukodono,
            Sukokerto,
            Sukowono,
        ];
    }
});

// Kec. Grujugan
loadGeoJSONFiles("FGrujugan", () => {
    if (geoJSONData["Kec Grujugan"]) {
        geoJSONData["Kec Grujugan"] = [
            Dadapan,
            Dawuhan,
            GrujuganKidul,
            Kabuaran,
            Kejawan,
            Pekauman,
            SumberPandan,
            Taman,
            TegalMijin,
            Wanisodo,
            Wonosari,
        ];
    }
});

// Kec. Curahdami
loadGeoJSONFiles("GCurahdami", () => {
    if (geoJSONData["Kec Curahdami"]) {
        geoJSONData["Kec Curahdami"] = [
            Curahdami,
            Curahpoh,
            Jetis,
            Kupang,
            Locare,
            Pakuwesi,
            Panambangan,
            Petung,
            Poncogati,
            Selolembu,
            SumberSalak,
            Sumbersuko,
        ];
    }
});

// Kec. Tenggarang
loadGeoJSONFiles("HTenggarang", () => {
    if (geoJSONData["Kec Tenggarang"]) {
        geoJSONData["Kec Tenggarang"] = [
            Bataan,
            DawuhanTGR,
            Gebang,
            Kajar,
            Kesemek,
            KoncerDarulAman,
            KoncerKidul,
            Lojajar,
            Pekalangan,
            SumberSalam,
            TangsilKulon,
            Tenggarang,
        ];
    }
});

// Kec. Wonosari
loadGeoJSONFiles("IWonosari", () => {
    if (geoJSONData["Kec Wonosari"]) {
        geoJSONData["Kec Wonosari"] = [
            BendoArum,
            Jumpong,
            Kapuran,
            LombokKulon,
            LombokWetan,
            PasarRejo,
            Pelalangan,
            SumberKalong,
            TangsilWetan,
            Traktakan,
            Tumpeng,
            WonosariWN,
        ];
    }
});

// Kec. Tapen
loadGeoJSONFiles("JTapen", () => {
    if (geoJSONData["Kec Tapen"]) {
        geoJSONData["Kec Tapen"] = [
            Cindogo,
            GunungAnyar,
            JurangSapi,
            KaliTapen,
            MangliWetan,
            Mrawan,
            Taal,
            Tapen,
            Wonokusumo,
        ];
    }
});

// Kec. Bondowoso
loadGeoJSONFiles("KBondowoso", () => {
    if (geoJSONData["Kec Bondowoso"]) {
        geoJSONData["Kec Bondowoso"] = [
            Badean,
            Blindungan,
            Dabasah,
            Kademangan,
            KembangBWS,
            Kotakulon,
            Nangkaan,
            Pancoran,
            Pejaten,
            Sukowiryo,
            Tamansari,
        ];
    }
});

// Kec. Wringin
loadGeoJSONFiles("LWringin", () => {
    if (geoJSONData["Kec Wringin"]) {
        geoJSONData["Kec Wringin"] = [
            Ambulu,
            Ampelan,
            BanyuPutih,
            BanyuWulu,
            Bukor,
            Glingseran,
            Gubrih,
            JambeWungu,
            JatiSari,
            JatiTamban,
            SumberCanting,
            SumberMalang,
            Wringin,
        ];
    }
});

// Kec. Tegalampel
loadGeoJSONFiles("MTegalampel", () => {
    if (geoJSONData["Kec Tegalampel"]) {
        geoJSONData["Kec Tegalampel"] = [
            KarangAnyar,
            Klabang,
            KlabangAgung,
            Mandiro,
            Purnama,
            SekarPutih,
            TanggulAngin,
            Tegalampel,
        ];
    }
});

// Kec. Klabang
loadGeoJSONFiles("NKlabang", () => {
    if (geoJSONData["Kec Klabang"]) {
        geoJSONData["Kec Klabang"] = [
            Besuk,
            Blimbing,
            KarangAnyarKL,
            KarangSengon,
            KlabangKL,
            Klampokan,
            Leprak,
            Pandak,
            SumberSuko,
            Wonoboyo,
            Wonokerto,
        ];
    }
});

// Kec. Cermee
loadGeoJSONFiles("OCermee", () => {
    if (geoJSONData["Kec Cermee"]) {
        geoJSONData["Kec Cermee"] = [
            Bajuran,
            BatuAmpar,
            BatuSalang,
            Bercak,
            BercakAsri,
            Cermee,
            Grujugan,
            JirekMas,
            Kladi,
            Palalangan,
            RambanKulon,
            RambanWetan,
            Solor,
            SulingKulon,
            SulingWetan,
        ];
    }
});

// Kec. Prajekan
loadGeoJSONFiles("PPrajekan", () => {
    if (geoJSONData["Kec Prajekan"]) {
        geoJSONData["Kec Prajekan"] = [
            Bandilan,
            Cangkring,
            PrajekanKidul,
            PrajekanLor,
            Sempol,
            Tarum,
            Walidono,
        ];
    }
});

// Kec. Pakem
loadGeoJSONFiles("QPakem", () => {
    if (geoJSONData["Kec Pakem"]) {
        geoJSONData["Kec Pakem"] = [
            AndungSari,
            ArdiSaeng,
            GadingSari,
            KupangPK,
            Pakem,
            PatemonPK,
            PetungPK,
            SumberDumpyong,
        ];
    }
});

// Kec. SumberWringin
loadGeoJSONFiles("RSumberWringin", () => {
    if (geoJSONData["Kec SumberWringin"]) {
        geoJSONData["Kec SumberWringin"] = [
            RejoAgung,
            Sukorejo,
            SukorejoKidul,
            SumberGading,
            SumberWringin,
            TegalJati,
        ];
    }
});

// Kec. Sempol
loadGeoJSONFiles("SSempol", () => {
    if (geoJSONData["Kec Sempol"]) {
        geoJSONData["Kec Sempol"] = [
            Jampit,
            KaliAnyarSPL,
            KaliGedang,
            KalisatSPL,
            SempolSPL,
            SumberRejo,
        ];
    }
});

// Kec. Binakal
loadGeoJSONFiles("TBinakal", () => {
    if (geoJSONData["Kec Binakal"]) {
        geoJSONData["Kec Binakal"] = [
            Baratan,
            Bendelan,
            Binakal,
            GadingSariBKL,
            JerukSokSok,
            Kembangan,
            SumberTengah,
            SumberWaru,
        ];
    }
});

// Kec. TamanKrocok
loadGeoJSONFiles("UTamanKrocok", () => {
    if (geoJSONData["Kec Taman Krocok"]) {
        geoJSONData["Kec Taman Krocok"] = [
            Gentong,
            Kemuningan,
            Kretek,
            Paguan,
            SumberKokap,
            TamanTMK,
            Trebungan,
        ];
    }
});

// Kec. BotoLinggo
loadGeoJSONFiles("VBotoLinggo", () => {
    if (geoJSONData["Kec Botolinggo"]) {
        geoJSONData["Kec Botolinggo"] = [
            BotoLinggo,
            Gayam,
            GayamLor,
            Klekehan,
            Lanas,
            Lumutan,
            Penang,
            SumberCantingBTL,
        ];
    }
});

// Kec. Jambesari
loadGeoJSONFiles("WJambesari", () => {
    if (geoJSONData["Kec Jambesari"]) {
        geoJSONData["Kec Jambesari"] = [
            GrujuganLorJMB,
            JambeAnom,
            Jambesari,
            Pejagan,
            Pengarang,
            PucangAnom,
            SumberAnyarJMB,
            SumberJeruk,
            TegalPasir,
        ];
    }
});
// ----------------- end geojson -------------------

let map;
function loadMapsResultPreference(year) {
    const mapsContainerResultPreference = document.getElementById("map");
    if (map) {
        map.eachLayer((layer) => {
            if (!(layer instanceof L.TileLayer)) {
                map.removeLayer(layer);
            }
        });
    } else {
        // **Buat peta hanya jika belum ada**
        map = L.map("map").setView(
            [-7.902924194388354, 113.78138400430815],
            11
        );

        const tiles = L.tileLayer(
            "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
            {
                maxZoom: 19,
                attribution:
                    '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
            }
        ).addTo(map);
    }

    const cornIcon = L.icon({
        iconUrl: "/assets/images/website/corn.png", // Path ikon jagung
        iconSize: [50, 50], // Ukuran ikon
        iconAnchor: [16, 32], // Titik anchor
        popupAnchor: [0, -32], // Posisi popup
    });

    const riceIcon = L.icon({
        iconUrl: "/assets/images/website/rice.png", // Path ikon jagung
        iconSize: [50, 50], // Ukuran ikon
        iconAnchor: [16, 32], // Titik anchor
        popupAnchor: [0, -32], // Posisi popup
    });

    const cassavaIcon = L.icon({
        iconUrl: "/assets/images/website/cassava.png", // Path ikon jagung
        iconSize: [80, 80], // Ukuran ikon
        iconAnchor: [16, 32], // Titik anchor
        popupAnchor: [0, -32], // Posisi popup
    });

    const plantColors = {
        padi: "#28a745",
        jagung: "#ffc107",
        "ubi kayu": "#8B4513",
        default: "#6c757d",
    };

    // Array untuk menyimpan marker desa
    let villageMarkers = [];

    $.ajax({
        url: `/hasil-preferensi/getResultSubDistrictByYear/` + year,
        type: "GET",
        dataType: "json",
        success: function (data) {
            if (data["resultSubDistrictByYear"].length != 0) {
                // Memuat GeoJSON untuk setiap kecamatan
                Object.values(data["resultSubDistrictByYear"]).forEach(
                    (value) => {
                        // Menentukan tanaman dengan jumlah terbanyak
                        let mostPlanted = value["result"].reduce((max, plant) =>
                            plant["jumlah_tanaman"] > max["jumlah_tanaman"]
                                ? plant
                                : max
                        );

                        // Gunakan ikon sesuai dengan tanaman terbanyak
                        const marker = L.marker(
                            [value["latitude"], value["longitude"]],
                            {
                                icon:
                                    mostPlanted["jenis_tanaman"] === "padi"
                                        ? riceIcon
                                        : mostPlanted["jenis_tanaman"] ===
                                          "jagung"
                                        ? cornIcon
                                        : mostPlanted["jenis_tanaman"] ===
                                          "ubi kayu"
                                        ? cassavaIcon
                                        : new L.Icon.Default(),
                            }
                        )
                            .bindPopup(
                                `<div style="text-align: center;">
                                    <strong style="font-size: 14px; color: #2c3e50;">${value["subdistrict"]}</strong><br>
                                    Tanaman rekomendasi: <strong>${mostPlanted["jenis_tanaman"]}</strong> (${mostPlanted["jumlah_tanaman"]} bulan)
                                </div>`
                            )
                            .addTo(map);

                        marker.on("click", function () {
                            // Zoom ke lokasi kecamatan
                            map.setView(
                                [value["latitude"], value["longitude"]],
                                13
                            );

                            // Hapus semua layer GeoJSON sebelumnya
                            // (layer instanceof L.Marker && layer !== marker)
                            map.eachLayer(function (layer) {
                                if (layer instanceof L.GeoJSON) {
                                    map.removeLayer(layer);
                                }
                            });

                            // Hapus semua marker desa sebelumnya
                            villageMarkers.forEach((marker) =>
                                map.removeLayer(marker)
                            );
                            villageMarkers = []; // Kosongkan array setelah menghapus

                            // Tambahkan GeoJSON desa untuk kecamatan yang diklik
                            if (
                                typeof geoJSONData !== "undefined" &&
                                geoJSONData
                            ) {
                                const desaData =
                                    geoJSONData[value["subdistrict"]];

                                if (desaData && desaData.length > 0) {
                                    desaData.forEach((desa) => {
                                        L.geoJSON(desa, {
                                            style: function () {
                                                return {
                                                    color: plantColors[
                                                        mostPlanted[
                                                            "jenis_tanaman"
                                                        ]
                                                    ],
                                                    weight: 3,
                                                    fillColor: "#28a745",
                                                    fillOpacity: 1,
                                                };
                                            },
                                        }).addTo(map);
                                    });
                                } else {
                                    console.log(
                                        `No GeoJSON data available for ${value["subdistrict"]}`
                                    );
                                }
                            }

                            // Tambahkan ikon hasil dari desa
                            Object.values(data["resultVillageByYear"]).forEach(
                                (villagebyYear) => {
                                    if (
                                        value["sub_district_id"] ==
                                        villagebyYear["sub_district_id"]
                                    ) {
                                        // Menentukan tanaman dengan jumlah terbanyak
                                        let mostPlantedVillage = villagebyYear[
                                            "result"
                                        ].reduce((max, plant) =>
                                            plant["jumlah_tanaman"] >
                                            max["jumlah_tanaman"]
                                                ? plant
                                                : max
                                        );

                                        // marker per desa
                                        const villageMarker = L.marker(
                                            [
                                                villagebyYear["latitude"],
                                                villagebyYear["longitude"],
                                            ],
                                            {
                                                icon:
                                                    mostPlantedVillage[
                                                        "jenis_tanaman"
                                                    ] === "padi"
                                                        ? riceIcon
                                                        : mostPlantedVillage[
                                                              "jenis_tanaman"
                                                          ] === "jagung"
                                                        ? cornIcon
                                                        : mostPlantedVillage[
                                                              "jenis_tanaman"
                                                          ] === "ubi kayu"
                                                        ? cassavaIcon
                                                        : new L.Icon.Default(),
                                            }
                                        ).bindPopup(
                                            `<div style="text-align: center;">
                                                <strong style="font-size: 14px; color: #2c3e50;">${villagebyYear["village"]}</strong><br>
                                                Tanaman rekomendasi: <strong>${mostPlantedVillage["jenis_tanaman"]}</strong> (${mostPlantedVillage["jumlah_tanaman"]} bulan)
                                            </div>`
                                        );

                                        villageMarker.addTo(map);
                                        villageMarkers.push(villageMarker);
                                    }
                                }
                            );
                        });
                    }
                );
            } else {
                map.remove();
                map = null;

                mapsContainerResultPreference.innerHTML = `
                    <div style="display: flex; align-items: center; justify-content: center; 
                                height: 100%; text-align: center;">
                        <strong style="weight: 600;">Hitung preferensi kecamatan untuk tahun ${year} terlebih dahulu.</strong>
                    </div>
                `;
            }
        },
    });
}

let gridInstance;
function loadTableResultSubDistrict(year) {
    const tableContainerResultPreference = document.getElementById(
        "table-result-sub-district-by-year"
    );

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

    const monthNames = [
        "Januari",
        "Februari",
        "Maret",
        "April",
        "Mei",
        "Juni",
        "Juli",
        "Agustus",
        "September",
        "Oktober",
        "November",
        "Desember",
    ];

    $.ajax({
        url: `/hasil-preferensi/getResultSubDistrictByYear/` + year,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const listPlantArray = Object.values(data.listPlant);
            const resultSubDistrictByYearArray = Object.values(
                data.resultSubDistrictByYear
            );

            // Fungsi untuk memperbarui data berdasarkan kecamatan yang dipilih
            function updateTableData() {
                var choiceSubDistrict = $("#choiceSubDistrict").val();
                var choiceYear = $("#choiceYear").val();

                $("#spanYear").html(choiceYear);
                $("#spanSubDistrict").html(choiceSubDistrict);

                var tableDataResultSubDistrictByYear =
                    resultSubDistrictByYearArray
                        .filter(
                            (item) => item["subdistrict"] === choiceSubDistrict
                        )
                        .flatMap((item) =>
                            item["list"].map((subDistrict) => [
                                monthNames[
                                    parseInt(subDistrict["bulan"], 10) - 1
                                ],
                                subDistrict["tanaman"],
                            ])
                        );

                if (gridInstance) {
                    gridInstance
                        .updateConfig({
                            data: tableDataResultSubDistrictByYear,
                        })
                        .forceRender();
                } else {
                    gridInstance = new gridjs.Grid({
                        columns: [{ name: "Bulan" }, { name: "Tanaman" }],
                        data: tableDataResultSubDistrictByYear,
                        search: true,
                        sort: true,
                        pagination: {
                            limit: 6,
                        },
                        language: {
                            noRecordsFound:
                                "Hitung Alternatif Kecamatan Terlebih Dahulu",
                        },
                    }).render(tableContainerResultPreference);
                }
            }

            // jalankan terlebih dahulu
            updateTableData();

            $("#choiceSubDistrict").on("change", function () {
                updateTableData();
            });
        },
    });
}
