document.addEventListener("DOMContentLoaded", function () {
    loadListAlternatifReferensiData();

    $("#btn-count-topsis").on("click", function () {
        let tableSections = [
            "#matriks-ternomalisasi-id",
            "#matriks-ternomalisasi-terbobot-id",
            "#solusi-ideal-id",
            "#solusi-ideal-terbobot-id",
            "#hasil-preferensi-id",
        ];

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

        $.ajax({
            url: "/alternatif-referensi/addPreferensiResultReferensi",
            method: "GET",
            dataType: "json",
            beforeSend: function () {
                NProgress.start();
            },
            success: function (response) {
                NProgress.done();
                console.log(response);
                if ((response.message = "success")) {
                    loadMatriksTernomalisasiReferensi();
                    loadTernomalisasiTerbobotReferensi();
                    loadSolusiIdealReferensi();
                    loadSolusiIdealTerbobotReferensi();
                    loadPreferensiReferensi();
                }
            },
            error: function (xhr) {
                NProgress.done();
                console.log("gagal");
            },
        });
    });

    $(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 alternatif referensi ?</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-referensi/deleteAlternatifReferensi/" + id;
            }
        });
    });
});

let gridInstance;

function loadListAlternatifReferensiData() {
    const tableContainerAlternatifReferensi = document.getElementById(
        "table-alternatif-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const groupByPlantArray = Object.values(data.groupByPlant);
            const listCriteriaArray = Object.values(data.listCriterias).sort(
                (a, b) => a.id - b.id
            );

            const tableDataReferensiAlternatif = groupByPlantArray.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.plant,
                        ...criteriaValues,
                        gridjs.html(`
                        <button type="button" class="btn btn-warning"
                            data-bs-toggle="modal"
                            data-bs-target="#btn-edit-${item.plant_id}">
                            Ubah
                        </button>
                        <button type="button" class="btn btn-danger btn-hapus-alternatif" id="btn-hapus"
                            data-id="${item.plant_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
                ),
            ];
            tableDataReferensiAlternatif.push(footerRow);

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

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

let gridInstance2;
function loadMatriksTernomalisasiReferensi() {
    const tableContainerMatriksTernomalisasi = document.getElementById(
        "table-matriks-ternomalisasi-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const matriksTernomalisasiReferensiArray = Object.values(
                data.matriksTernomalisasiReferensi
            );

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

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

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

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

                gridInstance2 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataMatriksTernomalisasiReferensi,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerMatriksTernomalisasi);
            }
        },
    });
}

let gridInstance3;
function loadTernomalisasiTerbobotReferensi() {
    const tableContainerTernomalisasiTerbobot = document.getElementById(
        "table-ternomalisasi-terbobot-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const ternomalisasiTerbobotReferensiArray = Object.values(
                data.ternomalisasiTerbobotReferensi
            );

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

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

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

                const columns = isMobile
                    ? [
                          "No",
                          "Tanaman",
                          ...ternomalisasiTerbobotReferensiArray[0][
                              "criteria"
                          ].map((item, index) => ({
                              id: `col_${index}`,
                              name: gridjs.html(
                                  `${item["status"]} / ${item["bobot"]}`
                              ),
                          })),
                      ]
                    : [
                          { name: "No", width: "5%" },
                          { name: "Tanaman", width: "15%" },
                          ...ternomalisasiTerbobotReferensiArray[0][
                              "criteria"
                          ].map((item, index) => ({
                              id: `col_${index}`,
                              name: gridjs.html(
                                  `${item["status"]} / ${item["bobot"]}`
                              ),
                              width: "10%",
                          })),
                      ];
                gridInstance3 = new gridjs.Grid({
                    columns: columns,
                    data: tableDataTernomalisasiTerbobotReferensi,
                    search: true,
                    sort: true,
                    pagination: {
                        limit: 5,
                    },
                }).render(tableContainerTernomalisasiTerbobot);
            }
        },
    });
}

let gridInstance4;
function loadSolusiIdealReferensi() {
    const tableContainerSolusiIdealReferensi = document.getElementById(
        "table-solusi-ideal-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const solusiIdealPositifArray = Object.values(
                data.solusiIdealPositif
            );

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

            const tableDataSolusiIdealReferensi = [
                ["Positif", ...solusiIdealPositifArray.map((val) => val)],
                ["Negatif", ...solusiIdealNegatifArray.map((val) => val)],
            ];

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

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

let gridInstance5;
function loadSolusiIdealTerbobotReferensi() {
    const tableContainerSolusiIdealTerbobotReferensi = document.getElementById(
        "table-solusi-ideal-terbobot-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanReferensiArray = Object.values(
                data.determinanReferensi
            );

            const tableDeterminanReferensi = determinanReferensiArray.map(
                (val, index) => [
                    index + 1,
                    val["plant"],
                    val["determinanPositif"],
                    val["determinanNegatif"],
                ]
            );

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

let gridInstance6;
function loadPreferensiReferensi() {
    const tableContainerPreferensiReferensi = document.getElementById(
        "table-preferensi-referensi"
    );

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

    $.ajax({
        url: `/alternatif-referensi/getListAlternatifReferensi`,
        type: "GET",
        dataType: "json",
        success: function (data) {
            const determinanReferensiArray = Object.values(
                data.determinanReferensi
            );

            const tableDataPreferensi = determinanReferensiArray.map(
                (val, index) => [
                    index + 1,
                    val["plant"],
                    (
                        val["determinanNegatif"] /
                        (val["determinanNegatif"] + val["determinanPositif"])
                    ).toFixed(5),
                ]
            );

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