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

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

        $("#span-year").text(year);
        loadParameterListHeightVillage(year, subDistrictId);
    });

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

        loadParameterListHeightVillage(year, subDistrictId);
    });

    $(document).on("click", ".btn-add-height-village", function () {
        var subDistrictId = $("#subDistrictId").val();

        if (subDistrictId) {
            // Kosongkan list desa saat kecamatan berubah
            $("#villageId")
                .empty()
                .append('<option value="">-- Pilih Desa --</option>');
            $.ajax({
                url:
                    "/list-parameter-ketinggian-desa/getVillage/" +
                    subDistrictId,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data["village"], function (key, village) {
                        $("#villageId").append(
                            `<option value="${village.id}">${village.village}</option>`
                        );
                    });
                },
            });
        }

        $(document).on("change", "#subDistrictId", function () {
            subDistrictId = $(this).val();
            if (subDistrictId) {
                // Kosongkan list desa saat kecamatan berubah
                $("#villageId")
                    .empty()
                    .append('<option value="">-- Pilih Desa --</option>');
                $.ajax({
                    url:
                        "/list-parameter-ketinggian-desa/getVillage/" +
                        subDistrictId,
                    type: "GET",
                    dataType: "json",
                    success: function (data) {
                        $.each(data["village"], function (key, village) {
                            $("#villageId").append(
                                `<option value="${village.id}">${village.village}</option>`
                            );
                        });
                    },
                });
            }
        });
    });

    $(document).on("click", ".btn-edit-height-village", function () {
        let heightVillageId = $(this).data("height-village-id");
        let subDistrictId = $(this).data("village-sub-district-id");
        let subDistrict = $(this).data("sub-district");
        let villageId = $(this).data("village-id");
        let village = $(this).data("village");
        let year = $(this).data("year");
        let height = $(this).data("height");

        $('[name="heightVillageId"]').val(heightVillageId);
        $('[name="subDistrictId"]').val(subDistrictId);
        $('[name="villageId"]').val(villageId);
        $('[name="subDistrictName"]').val(subDistrict).prop("readonly", true);
        $('[name="villageName"]').val(village).prop("readonly", true);
        $('[name="year"]').val(year).prop("readonly", true);
        $('[name="height"]').val(height);
    });

    $(document).on("click", "#btn-hapus", function () {
        let id = $(this).data("id");
        Swal.fire({
            html: '<div class="mt-3"><lord-icon src="https://cdn.lordicon.com/gsqxdxog.json" trigger="loop" colors="primary:#f7b84b,secondary:#f06548" style="width:100px;height:100px"></lord-icon><div class="mt-4 pt-2 fs-15 mx-5"><h4>Apakah anda benar ?</h4><p class="text-muted mx-4 mb-0">Anda benar, akan menghapus data ketinggian desa atau kelurahan (tahunan) ?</p></div></div>',
            showCancelButton: !0,
            confirmButtonClass: "btn btn-primary w-xs me-2 mb-1",
            confirmButtonText: "Ya, hapus!",
            cancelButtonClass: "btn btn-danger w-xs mb-1",
            buttonsStyling: !1,
            showCloseButton: !0,
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href =
                    "/list-parameter-ketinggian-desa/deleteListHeightVillage/" +
                    id;
            }
        });
    });
});

let gridInstance;
function loadParameterListHeightVillage(year, subDistrictId) {
    const tableContainerListHeightVillage = document.getElementById(
        "table-parameter-list-height-village"
    );

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

    $.ajax({
        url:
            "/list-parameter-ketinggian-desa/getDataParameterListHeightVillage/" +
            year +
            "/" +
            subDistrictId,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const TableListHeightVillage = data["listHeightVillage"].map(
                (item, index) => [
                    index + 1,
                    item["village"],
                    item["height"],
                    gridjs.html(`
                        <button type="button" class="btn btn-warning btn-edit-height-village"
                            data-bs-toggle="modal"
                            data-bs-target="#modal-edit"
                            data-height-village-id="${item.hv_id}"
                            data-village-id="${item.hv_village_id}"
                            data-village-sub-district-id="${item.village_sub_district_id}"
                            data-sub-district="${item.sub_district}"
                            data-village="${item.village}"
                            data-year = "${item.year}"
                            data-height = "${item.height}">
                            Ubah
                        </button>
                        <button type="button" class="btn btn-danger btn-hapus-height-village" id="btn-hapus"
                        data-id="${item.hv_id}">
                            Hapus
                        </button>
                    `),
                ]
            );

            if (gridInstance) {
                gridInstance
                    .updateConfig({
                        data: TableListHeightVillage, // Update data
                    })
                    .forceRender(); // Paksa render ulang
            } else {
                // Jika grid belum ada, buat grid baru
                gridInstance = new gridjs.Grid({
                    columns: [
                        "No",
                        "Desa / Kelurahan",
                        "Ketinggian Tempat",
                        "aksi",
                    ],
                    data: TableListHeightVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 10,
                    },
                }).render(tableContainerListHeightVillage);
            }
        },
    });
}
