document.addEventListener("DOMContentLoaded", function () {
    loadListAlternatifSubDistrict("01", "2021");

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

        $("#subDistrictId").val(subDistrictId);
        $("#subDistrict").val(subDistrict);
        $("#month").val(month);
        $("#year").val(year);

        // Parsing JSON dari data-criteria-sub-district dan data-criteria
        let criteriaSubDistrict = JSON.parse(
            $(this).attr("data-criteria-sub-district")
        );
        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 = criteriaSubDistrict.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();

        $.ajax({
            url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
            method: "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-plantBySubDistrict-id",
                    ];

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

                    loadMatriksTernomalisasiSubDistrict(month, years);
                    loadTernomalisasiTerbobotSubDistrict(month, years);
                    loadSolusiIdealSubDistrict(month, years);
                    loadSolusiIdealTerbobotSubDistrict(month, years);
                    loadPreferensiSubDistrict(month, years);
                    loadListPlantBySubDistrict(month, years);
                }
            },
            error: function (xhr) {
                NProgress.done();
                console.log("gagal");
            },
        });
    });

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

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

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

        loadListAlternatifSubDistrict(month, years);
    });

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

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

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

        loadListAlternatifSubDistrict(month, years);
    });

    $(document).on("click", "#btn-add-alternatif", function () {
        var month = $("#choiceMonth").val();
        var year = $("#choiceYear").val();

        // $('[name="month"]').val(month).attr("readonly", true);
        // $('[name="year"]').val(year).attr("readonly", true);
    });

    $(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 kecamatan ?</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-kecamatan/deleteAlternatifSubDistrict/" +
                    id +
                    "/" +
                    month +
                    "/" +
                    year;
            }
        });
    });

    $("#btn-update-alternatif-sub-district").on("click", function () {
        var years = $("#choiceYear").val();
        var month = $("#choiceMonth").val();

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

        $.ajax({
            url: "/alternatif-kecamatan/" + month + "/" + 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 = "/alternatif-kecamatan";
                }, 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-kecamatan";
                }, 1000);
            },
        });
    });
});

let gridInstance;
function loadListAlternatifSubDistrict(month, years) {
    const tableContainerAlternatifSubDistrict = document.getElementById(
        "table-alternatif-sub-district"
    );

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        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 groupBySubDistrictArray = Object.values(
                    data.groupBySubDistrict
                );
                const listCriteriaArray = Object.values(
                    data.listCriterias
                ).sort((a, b) => a.id - b.id);

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

                const tableDataAlternatifSubDistrict =
                    groupBySubDistrictArray.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.sub_district,
                            ...criteriaValues,
                            gridjs.html(`
                            <button type="button" class="btn btn-warning btn-edit-alternatif"
                                data-bs-toggle="modal"
                                data-bs-target="#modal-edit"
                                data-sub-district-id="${item.sub_district_id}"
                                data-sub-district="${item.sub_district}"
                                data-year = "${item.year}"
                                data-month = "${item.month}"
                                data-criteria-sub-district='${JSON.stringify(
                                    item.criteria
                                )}'
                                data-criteria='${JSON.stringify(
                                    listCriteriaArray
                                )}'>
                                Ubah
                            </button>
                            <button type="button" class="btn btn-danger btn-hapus-plant" id="btn-hapus"
                                data-id="${item.sub_district_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
                    ),
                ];
                tableDataAlternatifSubDistrict.push(footerRow);

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

                    const columns = isMobile
                        ? [
                              "No",
                              "Kecamatan",
                              ...listCriteriaArray.map((item, index) => ({
                                  id: `col_${index}`,
                                  name: gridjs.html(`${item["criteria"]}`),
                              })),
                              "Aksi",
                          ]
                        : [
                              { name: "No", width: "5%" },
                              { name: "Kecamatan", 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: tableDataAlternatifSubDistrict,
                        search: true,
                        sort: true,
                        pagination: {
                            limit: 5,
                        },
                    }).render(tableContainerAlternatifSubDistrict);
                }
            }
        },
    });
}

let gridInstance2;
function loadMatriksTernomalisasiSubDistrict(month, years) {
    const tableContainerMatriksTernomalisasiSubDistrict =
        document.getElementById("table-matriks-ternomalisasi-sub-district");

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const matriksTernomalisasiSubDistrictArray = Object.values(
                data.matriksTernomalisasiSubDistrict
            );

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

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

            const isMobile = window.innerWidth < 768;

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

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

let gridInstance3;
function loadTernomalisasiTerbobotSubDistrict(month, years) {
    const tableContainerTernomalisasiTerbobotSubDistrict =
        document.getElementById("table-ternomalisasi-terbobot-sub-district");

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const ternomalisasiTerbobotSubDistrictArray = Object.values(
                data.ternomalisasiTerbobotSubDistrict
            );

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

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

            const isMobile = window.innerWidth < 768;

            const columns = isMobile
                ? [
                      "No",
                      "Kecamatan",
                      ...ternomalisasiTerbobotSubDistrictArray[0][
                          "criteria"
                      ].map((item, index) => ({
                          id: `col_${index}`,
                          name: gridjs.html(
                              `${item["status"]} / ${item["bobot"]}`
                          ),
                      })),
                  ]
                : [
                      { name: "No", width: "5%" },
                      { name: "Kecamatan", width: "15%" },
                      ...ternomalisasiTerbobotSubDistrictArray[0][
                          "criteria"
                      ].map((item, index) => ({
                          id: `col_${index}`,
                          name: gridjs.html(
                              `${item["status"]} / ${item["bobot"]}`
                          ),
                          width: "10%",
                      })),
                  ];

            if (gridInstance3) {
                gridInstance3
                    .updateConfig({
                        columns: columns,
                        data: tableDataTernomalisasiTerbobotSubDistrict,
                    })
                    .forceRender();
            } else {
                gridInstance3 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataTernomalisasiTerbobotSubDistrict,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerTernomalisasiTerbobotSubDistrict);
            }
        },
    });
}

let gridInstance4;
function loadSolusiIdealSubDistrict(month, years) {
    const tableContainerSolusiIdealSubDistrict = document.getElementById(
        "table-solusi-ideal-sub-district"
    );

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

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

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

            const tableDataSolusiIdealSubDistrict = [
                [
                    "Positif",
                    ...solusiIdealPositifSubDistrictArray.map((val) => val),
                ],
                [
                    "Negatif",
                    ...solusiIdealNegatifSubDistrictArray.map((val) => val),
                ],
            ];

            const isMobile = window.innerWidth < 768;

            const columns = isMobile
                ? [
                      { id: "type", name: "Solusi Ideal" },
                      ...solusiIdealPositifSubDistrictArray.map((_, index) => ({
                          id: `col_${index}`,
                          name: `Kriteria ${index + 1}`,
                      })),
                  ]
                : [
                      { id: "type", name: "Solusi Ideal", width: "20%" },
                      ...solusiIdealPositifSubDistrictArray.map((_, index) => ({
                          id: `col_${index}`,
                          name: `Kriteria ${index + 1}`,
                          width: "10%",
                      })),
                  ];

            if (gridInstance4) {
                gridInstance4
                    .updateConfig({
                        columns: columns,
                        data: tableDataSolusiIdealSubDistrict,
                    })
                    .forceRender();
            } else {
                gridInstance4 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataSolusiIdealSubDistrict,
                    search: false, // Tidak perlu pencarian
                    sort: false, // Tidak perlu sorting
                    pagination: false, // Hanya 2 baris, tidak perlu paginasi
                }).render(tableContainerSolusiIdealSubDistrict);
            }
        },
    });
}

let gridInstance5;
function loadSolusiIdealTerbobotSubDistrict(month, years) {
    const tableContainerSolusiIdealTerbobot = document.getElementById(
        "table-solusi-ideal-terbobot-sub-district"
    );

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanSubDistrictArray = Object.values(
                data.determinanSubDistrict
            );

            const tableDataDeterminanSubDistrict =
                determinanSubDistrictArray.map((val, index) => [
                    index + 1,
                    val["sub_district"],
                    val["determinanPositif"],
                    val["determinanNegatif"],
                ]);

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

let gridInstance6;
function loadPreferensiSubDistrict(month, years) {
    const tableContainerPreferensiSubDitrict = document.getElementById(
        "table-hasil-preferensi-sub-district"
    );

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanSubDistrictArray = Object.values(
                data.determinanSubDistrict
            );

            const tableDataPreferensiSubDistrict =
                determinanSubDistrictArray.map((val, index) => [
                    index + 1,
                    val["sub_district"],
                    (
                        val["determinanNegatif"] /
                        (val["determinanNegatif"] + val["determinanPositif"])
                    ).toFixed(5),
                ]);

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

let gridInstance7;
function loadListPlantBySubDistrict(month, years) {
    const tableContainerPlantBySubDistrict = document.getElementById(
        "table-hasil-plantBySubDistrict"
    );

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

    $.ajax({
        url: `/alternatif-kecamatan/getAlternatifSubDistrict/${month}/${years}`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const plantBySubDistrictArray = Object.entries(
                data.resultPlantBySubDistrict
            );

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

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