document.addEventListener("DOMContentLoaded", function () {
    loadListAlterntifVillage("01", "2021", "15");
    $(document).on("click", ".btn-add-alternatif-village", function () {
        var subDistrictId = $("#subDistrictId").val();

        if (subDistrictId) {
            // Kosongkan list desa saat kecamatan berubah
            $("#villageIdInput")
                .empty()
                .append('<option value="">-- Pilih Desa --</option>');

            $.ajax({
                url: "/alternatif-desa/getVillage/" + subDistrictId,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data["village"], function (key, village) {
                        $("#villageIdInput").append(
                            `<option value="${village.id}">${village.village}</option>`
                        );
                    });
                },
            });
        }

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

    $(document).on("click", ".btn-edit-alternatif", function () {
        let villageId = $(this).data("village-id");
        let village = $(this).data("village");
        let month = $(this).data("month");
        let year = $(this).data("year");

        $("#villageId").val(villageId);
        $("#village").val(village);
        $("#month").val(month);
        $("#year").val(year);

        // Parsing JSON dari data-criteria-sub-district dan data-criteria
        let criteriaVillage = JSON.parse($(this).attr("data-criteria-village"));
        let criteriaList = JSON.parse($(this).attr("data-criteria"));

        // // Kosongkan inputan sebelumnya
        $("#criteriaFields").empty();

        // // Loop criteria dan buat input dinamis
        $.each(criteriaList, function (index, crit) {
            let foundCrit = criteriaVillage.find(
                (item) => item.criteria_id === crit.id
            );
            let value = foundCrit ? foundCrit.value_alternatif : "";
            let criteriaName = crit.criteria.replace(/\s+/g, "");

            let inputField = `
                <div class="col-lg-6 mb-2">
                    <div>
                        <label for="${criteriaName}" class="form-label">
                            Masukkan ${crit.criteria}
                        </label>
                        <input type="text" class="form-control mb-1 criteria-input"
                            id="${criteriaName}" name="${crit.criteria}"
                            placeholder="Masukkan nilai kriteria" required value="${value}"
                        >
                    </div>
                </div>`;

            $("#criteriaFields").append(inputField);
        });
    });

    $(document).on("input", ".criteria-input", function () {
        this.value = this.value
            .replace(/[^0-9.]/g, "")
            .replace(/^\.+|\.\.+/g, "")
            .replace(/(\.\d*)\./g, "$1");
    });

    $(document).on("input", ".year-input", function () {
        this.value = this.value
            .replace(/\D/g, "") // Hanya angka
            .slice(0, 4); // Maksimal 4 digit
    });

    $("#btn-count-topsis").on("click", function () {
        month = $("#choiceMonth").val();
        years = $("#choiceYear").val();
        subDistrictId = $("#choiceSubDistrict").val();

        $.ajax({
            url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                NProgress.start();
            },
            success: function (response) {
                NProgress.done();
                if ((response.message = "success")) {
                    let tableSections = [
                        "#matriks-ternomalisasi-id",
                        "#matriks-ternomalisasi-terbobot-id",
                        "#solusi-ideal-id",
                        "#solusi-ideal-terbobot-id",
                        "#hasil-preferensi-id",
                        "#hasil-plantByVillage-id",
                    ];

                    tableSections.forEach((id) => {
                        $(id).removeClass("d-none").addClass("d-block");
                    });

                    loadMatriksTernomalisasiVillage(
                        month,
                        years,
                        subDistrictId
                    );
                    loadTernomalisasiTerbobotVillage(
                        month,
                        years,
                        subDistrictId
                    );
                    loadSolusiIdealVillage(month, years, subDistrictId);
                    loadSolusiIdealTerbobotVillage(month, years, subDistrictId);
                    loadPreferensiVillage(month, years, subDistrictId);
                    loadListPlantByVillage(month, years, subDistrictId);
                }
            },
            error: function (xhr) {
                NProgress.done();
                console.log("gagal");
            },
        });
    });

    $("#choiceMonth").on("change", function () {
        month = $(this).val();
        years = $("#choiceYear").val();
        subDistrictId = $("#choiceSubDistrict").val();

        let tableSections = [
            "#matriks-ternomalisasi-id",
            "#matriks-ternomalisasi-terbobot-id",
            "#solusi-ideal-id",
            "#solusi-ideal-terbobot-id",
            "#hasil-preferensi-id",
            "#hasil-plantByVillage-id",
        ];

        tableSections.forEach((id) => {
            $(id).removeClass("d-block").addClass("d-none");
        });

        $("#btn-count-topsis").removeClass("d-block").addClass("d-none");
        loadListAlterntifVillage(month, years, subDistrictId);
    });

    $("#choiceYear").on("change", function () {
        years = $(this).val();
        month = $("#choiceMonth").val();
        subDistrictId = $("#choiceSubDistrict").val();

        let tableSections = [
            "#matriks-ternomalisasi-id",
            "#matriks-ternomalisasi-terbobot-id",
            "#solusi-ideal-id",
            "#solusi-ideal-terbobot-id",
            "#hasil-preferensi-id",
            "#hasil-plantByVillage-id",
        ];

        tableSections.forEach((id) => {
            $(id).removeClass("d-block").addClass("d-none");
        });

        $("#btn-count-topsis").removeClass("d-block").addClass("d-none");
        loadListAlterntifVillage(month, years, subDistrictId);
    });

    $("#choiceSubDistrict").on("change", function () {
        subDistrictId = $(this).val();
        years = $("#choiceYear").val();
        month = $("#choiceMonth").val();

        let tableSections = [
            "#matriks-ternomalisasi-id",
            "#matriks-ternomalisasi-terbobot-id",
            "#solusi-ideal-id",
            "#solusi-ideal-terbobot-id",
            "#hasil-preferensi-id",
            "#hasil-plantByVillage-id",
        ];

        tableSections.forEach((id) => {
            $(id).removeClass("d-block").addClass("d-none");
        });

        $("#btn-count-topsis").removeClass("d-block").addClass("d-none");
        loadListAlterntifVillage(month, years, subDistrictId);
    });

    $(document).on("click", "#btn-hapus", function () {
        let id = $(this).data("id");
        let month = $("#choiceMonth").val();
        let year = $("#choiceYear").val();

        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 alternatif desa atau kelurahan ?</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 =
                    "/alternatif-desa/deleteAlternatifVillage/" +
                    id +
                    "/" +
                    month +
                    "/" +
                    year;
            }
        });
    });

    $("#btn-update-alternatif-village").on("click", function () {
        const month = $("#choiceMonth").val();
        const years = $("#choiceYear").val();
        const subDistrictId = $("#choiceSubDistrict").val();

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

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

let gridInstance;
function loadListAlterntifVillage(month, years, subDistrictId) {
    const tableContainerAlternatifVillage = document.getElementById(
        "table-alternatif-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            if (data.message == "Data tidak ditemukan") {
                $("#btn-count-topsis")
                    .removeClass("d-block")
                    .addClass("d-none");
            } else {
                $("#btn-count-topsis")
                    .removeClass("d-none")
                    .addClass("d-block");

                const groupByVillageArray = Object.values(data.groupByVillage);

                const listCriteriaArray = Object.values(
                    data.listCriterias
                ).sort((a, b) => a.id - b.id);

                // jika jumlah alternatif kurang dari 2 tidak dapat dihitung
                if (groupByVillageArray.length < 2) {
                    $("#btn-count-topsis")
                        .removeClass("d-block")
                        .addClass("d-none");
                }

                const tableDataAlternatifVillage = groupByVillageArray.map(
                    (item, index) => {
                        const criteriaValues = listCriteriaArray.map(
                            (criteriaItem) => {
                                // Cari nilai yang sesuai dengan ID kriteria
                                const foundCriteria = item.criteria.find(
                                    (crit) =>
                                        crit.criteria_id === criteriaItem.id
                                );
                                return foundCriteria
                                    ? foundCriteria.value_alternatif
                                    : "";
                            }
                        );

                        // jika data belum lengkap tidak dapat dihitung
                        const hasEmptyValue = criteriaValues.includes("");
                        if (hasEmptyValue) {
                            $("#btn-count-topsis").addClass("d-none");
                        }

                        return [
                            index + 1,
                            item.village,
                            ...criteriaValues,
                            gridjs.html(`
                            <button type="button" class="btn btn-warning btn-edit-alternatif"
                                data-bs-toggle="modal"
                                data-bs-target="#modal-edit"
                                data-village-id="${item.village_id}"
                                data-village="${item.village}"
                                data-year = "${item.year}"
                                data-month = "${item.month}"
                                data-criteria-village='${JSON.stringify(
                                    item.criteria
                                )}'
                                data-criteria='${JSON.stringify(
                                    listCriteriaArray
                                )}'>
                                Ubah
                            </button>
                            <button type="button" class="btn btn-danger btn-hapus-village" id="btn-hapus"
                                data-id="${item.village_id}">
                                Hapus
                            </button>`),
                        ];
                    }
                );

                // ambil status dan bobot
                const criteriaTypes = listCriteriaArray.map(
                    (crit) => crit.status
                );
                const criteriaBobot = listCriteriaArray.map(
                    (crit) => crit.bobot
                );

                const footerRow = [
                    "",
                    gridjs.html(`<b>Keterangan</b> / <b>Bobot</b>`), // Dua baris dalam satu sel
                    ...criteriaTypes.map(
                        (status, index) =>
                            gridjs.html(`${status} / ${criteriaBobot[index]}`) // Gabungkan per kolom
                    ),
                ];
                tableDataAlternatifVillage.push(footerRow);

                if (gridInstance) {
                    gridInstance
                        .updateConfig({
                            data: tableDataAlternatifVillage,
                        })
                        .forceRender();
                } else {
                    const isMobile = window.innerWidth < 768;

                    const columns = isMobile
                        ? [
                              "No",
                              "desa",
                              ...listCriteriaArray.map((item, index) => ({
                                  id: `col_${index}`,
                                  name: gridjs.html(`${item["criteria"]}`),
                              })),
                              "Aksi",
                          ]
                        : [
                              { name: "No", width: "5%" },
                              { name: "desa", width: "15%" },
                              ...listCriteriaArray.map((item, index) => ({
                                  id: `col_${index}`,
                                  name: gridjs.html(`${item["criteria"]}`),
                                  width: "10%",
                              })),
                              { name: "Aksi", width: "20%" },
                          ];

                    gridInstance = new gridjs.Grid({
                        columns: columns,
                        data: tableDataAlternatifVillage,
                        search: true,
                        sort: true,
                        pagination: {
                            limit: 6,
                        },
                    }).render(tableContainerAlternatifVillage);
                }
            }
        },
    });
}

let gridInstance2;
function loadMatriksTernomalisasiVillage(month, years, subDistrictId) {
    const tableContainerMatriksTernomalisasiVillage = document.getElementById(
        "table-matriks-ternomalisasi-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const matriksTernomalisasiVillageArray = Object.values(
                data.matriksTernomalisasiVillage
            );

            const tableDataMatriksTernomalisasiVillage =
                matriksTernomalisasiVillageArray.map((item, index) => {
                    const criteriaValues = item.criteria.map(
                        (crit) => crit.value_alternatif
                    );

                    return [index + 1, item.village, ...criteriaValues];
                });

            const isMobile = window.innerWidth < 768;

            const columns = isMobile
                ? [
                      "No",
                      "Desa",
                      ...data["pembagiMatriksTernomalisasi"].map(
                          (item, index) => ({
                              id: `col_${index}`,
                              name: item,
                          })
                      ),
                  ]
                : [
                      { name: "No", width: "5%" },
                      { name: "Desa", width: "15%" },
                      ...data["pembagiMatriksTernomalisasi"].map(
                          (item, index) => ({
                              id: `col_${index}`,
                              name: item,
                              width: "10%",
                          })
                      ),
                  ];

            if (gridInstance2) {
                gridInstance2
                    .updateConfig({
                        columns: columns,
                        data: tableDataMatriksTernomalisasiVillage,
                    })
                    .forceRender();
            } else {
                gridInstance2 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataMatriksTernomalisasiVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 6,
                    },
                }).render(tableContainerMatriksTernomalisasiVillage);
            }
        },
    });
}

let gridInstance3;
function loadTernomalisasiTerbobotVillage(month, years, subDistrictId) {
    const tableContainerTernomalisasiTerbobotVillage = document.getElementById(
        "table-ternomalisasi-terbobot-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const ternomalisasiTerbobotVillageArray = Object.values(
                data.ternomalisasiTerbobotVillage
            );

            const tableDataTernomalisasiTerbobotVillage =
                ternomalisasiTerbobotVillageArray.map((item, index) => {
                    const criteriaValues = item.criteria.map(
                        (crit) => crit.value_alternatif
                    );

                    return [index + 1, item.village, ...criteriaValues];
                });

            const isMobile = window.innerWidth < 768;

            const columns = isMobile
                ? [
                      "No",
                      "Desa",
                      ...ternomalisasiTerbobotVillageArray[0]["criteria"].map(
                          (item, index) => ({
                              id: `col_${index}`,
                              name: gridjs.html(
                                  `${item["status"]} / ${item["bobot"]}`
                              ),
                          })
                      ),
                  ]
                : [
                      { name: "No", width: "5%" },
                      { name: "Desa", width: "15%" },
                      ...ternomalisasiTerbobotVillageArray[0]["criteria"].map(
                          (item, index) => ({
                              id: `col_${index}`,
                              name: gridjs.html(
                                  `${item["status"]} / ${item["bobot"]}`
                              ),
                              width: "10%",
                          })
                      ),
                  ];
            if (gridInstance3) {
                gridInstance3
                    .updateConfig({
                        columns: columns,
                        data: tableDataTernomalisasiTerbobotVillage,
                    })
                    .forceRender();
            } else {
                gridInstance3 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataTernomalisasiTerbobotVillage,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 6,
                    },
                }).render(tableContainerTernomalisasiTerbobotVillage);
            }
        },
    });
}

let gridInstance4;
function loadSolusiIdealVillage(month, years, subDistrictId) {
    const tableContainerSolusiIdealVillage = document.getElementById(
        "table-solusi-ideal-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const solusiIdealPositifVillageArray = Object.values(
                data.solusiIdealPositif
            );

            const solusiIdealNegatifVillageArray = Object.values(
                data.solusiIdealNegatif
            );

            const tableDataSolusiIdealVillage = [
                [
                    "Positif",
                    ...solusiIdealPositifVillageArray.map((val) => val),
                ],
                [
                    "Negatif",
                    ...solusiIdealNegatifVillageArray.map((val) => val),
                ],
            ];

            const isMobile = window.innerWidth < 768;

            const columns = isMobile
                ? [
                      { id: "type", name: "Solusi Ideal" },
                      ...solusiIdealPositifVillageArray.map((_, index) => ({
                          id: `col_${index}`,
                          name: `Kriteria ${index + 1}`,
                      })),
                  ]
                : [
                      { id: "type", name: "Solusi Ideal", width: "20%" },
                      ...solusiIdealPositifVillageArray.map((_, index) => ({
                          id: `col_${index}`,
                          name: `Kriteria ${index + 1}`,
                          width: "10%",
                      })),
                  ];
            if (gridInstance4) {
                gridInstance4
                    .updateConfig({
                        columns: columns,
                        data: tableDataSolusiIdealVillage,
                    })
                    .forceRender();
            } else {
                gridInstance4 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataSolusiIdealVillage,
                    search: false, // Tidak perlu pencarian
                    sort: false, // Tidak perlu sorting
                    pagination: false, // Hanya 2 baris, tidak perlu paginasi
                }).render(tableContainerSolusiIdealVillage);
            }
        },
    });
}

let gridInstance5;
function loadSolusiIdealTerbobotVillage(month, years, subDistrictId) {
    const tableContainerSolusiIdealTerbobot = document.getElementById(
        "table-solusi-ideal-terbobot-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanVillageArray = Object.values(
                data.determinanVillage
            );

            const tableDataDeterminanVillage = determinanVillageArray.map(
                (val, index) => [
                    index + 1,
                    val["village"],
                    val["determinanPositif"],
                    val["determinanNegatif"],
                ]
            );

            if (gridInstance5) {
                gridInstance5
                    .updateConfig({
                        columns: [
                            { name: "No", width: "10%" },
                            { name: "Desa", width: "30%" },
                            { name: "D+", width: "30%" },
                            { name: "D-", width: "30%" },
                        ],
                        data: tableDataDeterminanVillage,
                    })
                    .forceRender();
            } else {
                gridInstance5 = new gridjs.Grid({
                    columns: [
                        { name: "No", width: "10%" },
                        { name: "Desa", width: "30%" },
                        { name: "D+", width: "30%" },
                        { name: "D-", width: "30%" },
                    ],
                    data: tableDataDeterminanVillage,
                    search: true,
                    sort: true,
                    pagination: { limit: 6 },
                    resizable: true,
                }).render(tableContainerSolusiIdealTerbobot);
            }
        },
    });
}

let gridInstance6;
function loadPreferensiVillage(month, years, subDistrictId) {
    const tableContainerPreferensiVillage = document.getElementById(
        "table-hasil-preferensi-village"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanVillageArray = Object.values(
                data.determinanVillage
            );

            const tableDataPreferensiVillage = determinanVillageArray.map(
                (val, index) => [
                    index + 1,
                    val["village"],
                    (
                        val["determinanNegatif"] /
                        (val["determinanNegatif"] + val["determinanPositif"])
                    ).toFixed(5),
                ]
            );

            if (gridInstance6) {
                gridInstance6
                    .updateConfig({
                        columns: [
                            { name: "No", width: "10%" },
                            { name: "Desa", width: "30%" },
                            { name: "Nilai Preferensi", width: "30%" },
                        ],
                        data: tableDataPreferensiVillage,
                    })
                    .forceRender();
            } else {
                gridInstance6 = new gridjs.Grid({
                    columns: [
                        { name: "No", width: "10%" },
                        { name: "Desa", width: "30%" },
                        { name: "Nilai Preferensi", width: "30%" },
                    ],
                    data: tableDataPreferensiVillage,
                    search: true,
                    sort: true,
                    pagination: { limit: 6 },
                    resizable: true,
                }).render(tableContainerPreferensiVillage);
            }
        },
    });
}

let gridInstance7;
function loadListPlantByVillage(month, years, subDistrictId) {
    const tableContainerPlantByVillage = document.getElementById(
        "table-hasil-plantByVillage"
    );

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

    $.ajax({
        url: `/alternatif-desa/getAlternatifVillage/${month}/${years}/${subDistrictId}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const plantByVillageArray = Object.entries(
                data.resultPlantByVillage
            );

            const tableDataPlantByVillage = plantByVillageArray.map(
                (val, index) => [index + 1, val[0], val[1]]
            );

            if (gridInstance7) {
                gridInstance7
                    .updateConfig({
                        columns: [
                            { name: "No", width: "10%" },
                            { name: "Desa", width: "30%" },
                            { name: "Tanaman", width: "30%" },
                        ],
                        data: tableDataPlantByVillage,
                    })
                    .forceRender();
            } else {
                gridInstance7 = new gridjs.Grid({
                    columns: [
                        { name: "No", width: "10%" },
                        { name: "Desa", width: "30%" },
                        { name: "Tanaman", width: "30%" },
                    ],
                    data: tableDataPlantByVillage,
                    search: true,
                    sort: true,
                    pagination: { limit: 6 },
                    resizable: true,
                    language: {
                        noRecordsFound:
                            "Hitung Prefrensi Tanaman Terlebih Dahulu",
                    },
                    noRecordsFound: "Hitung Preferensi Tanaman Terlebih Dahulu",
                }).render(tableContainerPlantByVillage);
            }
        },
    });
}
