import {
    triggerMessage
} from './module/messages.js';
var gHorarios = [];

/**@Auxiliary functions */
function listProfesor({
    id,
    grado,
    profesor,
    clave
}) {
    const li = document.createElement('li');
    li.setAttribute('data-id', id);
    li.classList.add('list-group-item', 'd-flex', 'justify-content-between', 'align-items-center');
    li.innerHTML = `${clave} | ${grado} ${profesor}`

    const btn = document.createElement('button');
    btn.setAttribute('type', 'button');
    btn.classList.add('badge', 'badge-danger', 'badge-pill', 'border-0');
    btn.onclick = _ => li.remove();

    const i = document.createElement('i');
    i.classList.add('ing-cancelar');
    btn.appendChild(i);
    li.appendChild(btn);

    document.getElementById("profesores").appendChild(li);
}
// function for comparing two hours in format hh:mm (24 hours) and return the spaceship operator
function compareHours(hora1, hora2) {
    // parseInt each hour and minute
    const [h1, m1, ] = hora1.split(":").map(x => parseInt(x));
    const [h2, m2, ] = hora2.split(":").map(x => parseInt(x));

    if (h1 > h2)
        return 1;
    else if (h1 < h2)
        return -1;
    else if (m1 > m2)
        return 1;
    else if (m1 < m2)
        return -1;
    else
        return 0;
}
async function buscarGrupo() {

    // Add loading animation in the button
    const btn = document.querySelector("#btn-buscar");
    btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Cargando...';
    btn.disabled = true;

    const carrera = document.querySelector("#filter_carrera").value;
    const grupo = document.querySelector("#filter_grupo").value;

    if (carrera == "" || grupo == "") {
        triggerMessage("El nombre del grupo y la carrera son requeridos", "Faltan campos");

        // Remove loading animation in the button
        btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
        btn.disabled = false;

        return;
    }
    const formData = new FormData();

    formData.append("carrera", carrera);
    formData.append("grupo", grupo);
    formData.append("periodo", document.querySelector("#periodo").value);
    formData.append('facultad', '<?= $user->facultad['facultad_id'] ?>');

    try {
        gHorarios = [];
        const {
            status,
            horario: horarios,
        } = await fetch("action/action_horario.php", {
            method: "POST",
            body: formData
        }).then(res => res.json());

        if (status != "success") {
            triggerMessage(response.message, "Error");
            // Remove loading animation in the button
            btn.innerHTML = /* HTML */ `<i class="ing-buscar ing"></i> Buscar`;
            btn.disabled = false;
        }
        // show the table
        table.style.display = "table";
        document.querySelectorAll('.hidden').forEach(element => element.style.display = "block");
        // clear the table
        table.innerHTML = empty_table;

        if (horarios.length == 0) {
            // reload window
            window.location.reload();
            return;
        }
        // fill the table
        gHorarios = horarios;

        function conflicts(horario1, horario2) {
            const {
                hora: hora_inicio1,
                hora_final: hora_final1,
                dia: dia1,
            } = horario1;

            const {
                hora: hora_inicio2,
                hora_final: hora_final2,
                dia: dia2,
            } = horario2;


            // if the days are different, there is no conflict
            if (dia1 != dia2) {
                return false;
            }

            const compareInicios = compareHours(hora_inicio1, hora_inicio2);
            const compareFinales = compareHours(hora_final1, hora_final2);
            const compareInicioFinal = compareHours(hora_inicio1, hora_final2);
            const compareFinalInicio = compareHours(hora_final1, hora_inicio2);

            // if the horario is inside the other
            if (compareInicios === 0 || compareFinales === 0)
                return true
            if (compareInicios === 1 && compareInicioFinal === -1)
                return true
            if (compareFinales === -1 && compareFinalInicio === 1)
                return true

            // if the horario is outside the other
            if (compareInicios === -1 && compareFinales === 1)
                return true

            return false;
        }

        // remove the next 5 cells
        function removeNextCells(horas, minutos, dia, cells = 5) {
            [...Array(cells).keys()].map(i => i + 1).forEach(i => {
                const minute = (minutos + i * 15)
                const next_minute = (minute % 60).toString().padStart(2, "0");
                const next_hour = (horas + Math.floor(minute / 60))

                document.getElementById(`hora-${next_hour}:${next_minute}-${dia}`).remove()
            });
        }

        function newBlock(horario, edit = false) {
            function move(horario, cells) {
                const {
                    hora: hora_inicio,
                    dia,
                } = horario;

                const [horas, minutos] = hora_inicio.split(":").map(x => parseInt(x));

                const cell = document.getElementById(`hora-${horas}:${minutos.toString().padStart(2, "0")}-${dia}`);

                const {
                    top,
                    left
                } = cell.getBoundingClientRect();

                const block = document.getElementById(`block-${horario.id}`);

                block.style.top = `${top}px`;
                block.style.left = `${left}px`;

                removeNextCells(horas, minutos, dia, cells);
            }
            const {
                id,
                materia,
                salon,
                profesores,
                hora: hora_inicio,
                dia,
                bloques
            } = horario;

            const [horas, minutos] = hora_inicio.split(":").map(x => parseInt(x));
            const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
            horario.hora = hora;

            const cell = document.getElementById(`hora-${hora}-${dia}`);


            cell.dataset.ids = id;

            cell.innerHTML = /*html*/ `
                <small class="text-gray">${hora}</small> 
                <b class="title">${materia}</b> <br>
                <br><span>Salón: </span>${salon} <br>
                <small class="overflow-auto my-2" style="max-height: 3rem; display: block;">
                    ${profesores.map(({grado, profesor}) => /*html*/ ` <span class = "ing ing-formacion mx-1" > </span> ${grado} ${profesor}`).join("<br>")}
                </small>`

            if (edit)
                cell.innerHTML += /*html*/
                `<div class="menu-flotante p-2" style="opacity: .7;" >
                    <a class="mx-2" href="#" data-toggle="modal" data-target="#modal-editar">
                        <i class="ing-editar ing"></i>
                    </a>
                    <a class="mx-2" href="#" data-toggle="modal" data-target="#modal-borrar">
                        <i class="ing-basura ing" > </i>
                    </a>
                </div>
                `

            cell.classList.add("bloque-clase", "position-relative");
            cell.rowSpan = bloques;
            // draggable
            cell.draggable = <?= $write ? "true" : "false" ?>;

            bloques > 0 ? removeNextCells(horas, minutos, dia, bloques - 1) : null;
        }

        function newConflictBlock(horarios, edit = false) {
            const first_horario = horarios[0];
            const [horas, minutos] = first_horario.hora.split(":").map(x => parseInt(x));
            const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
            const ids = horarios.map(horario => horario.id);
            const cell = document.getElementById(`hora-${hora}-${first_horario.dia}`);
            if (cell == null) {
                console.error(`Error: No se encontró la celda: hora-${hora}-${first_horario.dia}`);
                return;
            }
            cell.dataset.ids = ids.join(",");

            // replace the content of the cell
            cell.innerHTML = /* HTML */ `
            <small class = 'text-danger'>
                ${hora}
            </small>
            <div class="d-flex justify-content-center align-items-center mt-4">
                <div class="d-flex flex-column justify-content-center align-items-center">
                    <span class="ing ing-importante text-danger" style="font-size: 2rem;"></span>
                    <b class='text-danger'>
                        Empalme de ${ids.length} horarios
                    </b> <hr>
                    <i class="text-danger">Ver horarios &#8230;</i>
                </div>
            </div>
            `;

            // the text must be centered
            // cell.style.backgroundColor = "#f6cfd6";
            cell.classList.add("conflict", "bloque-clase");
            // add cursor clickable role = "button"
            cell.setAttribute("role", "button");

            // add the event listener for the cell
            cell.addEventListener("click", () => {
                $("#modal-choose").modal("show");
                const ids = cell.getAttribute("data-ids").split(",").map(x => parseInt(x));
                const horarios = gHorarios.filter(horario => ids.includes(horario.id));
                const tbody = document.querySelector("#modal-choose tbody");
                tbody.innerHTML = "";
                horarios.sort((a, b) => compareHours(a.hora, b.hora)).forEach(horario => {
                    const {
                        materia,
                        dia,
                        hora,
                        hora_final,
                        profesores,
                        salon,
                        id,
                    } = horario;

                    // remove the last 00 of the hour
                    const [horaFmt, hora_finalFmt] = [hora, hora_final].map(hora => hora.slice(0, -3))
                    const buttons = /* HTML */ `
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary dismiss-editar" data-toggle="modal" data-target="#modal-editar">
                                    <i class="ing-editar ing"></i>
                                </button>
                            </td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-danger dismiss-editar" data-toggle="modal" data-target="#modal-borrar">
                                    <i class="ing-basura ing"></i>
                                </button>
                            </td>`

                    tbody.innerHTML += /* HTML */ `
                        <tr data-ids="${id}">
                            <td><small>${horaFmt}-${hora_finalFmt}</small></td>
                            <td>${materia}</td>
                            <td>
                                ${profesores.map(({ grado, profesor }) => `${grado} ${profesor}`).join(", ")}
                            </td>
                            <td>${salon}</td>
                            ${edit ? buttons : ""}
                        </tr>`;
                });

                document.querySelectorAll(".dismiss-editar").forEach(btn => {
                    btn.addEventListener("click", () => $("#modal-choose").modal("hide"));
                });

            });

            // blocks is (firsthour - lasthour) / 15 minutes
            // sum the duracion_bloques of each horario
            function getDuration(hora_i, hora_f) {
                const [horas_i, minutos_i] = hora_i.split(":").map(x => parseInt(x));
                const [horas_f, minutos_f] = hora_f.split(":").map(x => parseInt(x));
                const date_i = new Date(0, 0, 0, horas_i, minutos_i);
                const date_f = new Date(0, 0, 0, horas_f, minutos_f);
                const diff = date_f - date_i;
                return diff / (1000 * 60 * 15);
            }

            const lastHorario = horarios[horarios.length - 1];
            // remove the next cells
            // get the max hora_final
            const maxHoraFinal = horarios.reduce((max, horario) => {
                const [horas, minutos] = horario.hora_final.split(":").map(x => parseInt(x));
                const date = new Date(0, 0, 0, horas, minutos);
                return date > max ? date : max;
            }, new Date(0, 0, 0, 0, 0));

            const blocks = getDuration(first_horario.hora, `${maxHoraFinal.getHours()}:${maxHoraFinal.getMinutes()}`);
            cell.rowSpan = blocks
            removeNextCells(horas, minutos, first_horario.dia, blocks - 1);
        }

        const conflictBlocks = horarios.filter((horario, index, arrayHorario) =>
                arrayHorario.filter((_, i) => i != index).some(horario2 =>
                    conflicts(horario, horario2)))
            .sort((a, b) => compareHours(a.hora, b.hora));

        const classes = horarios.filter(horario => !conflictBlocks.includes(horario));

        const conflictBlocksPacked = []; // array of sets
        conflictBlocks.forEach(horario => {
            const setIndex = conflictBlocksPacked.findIndex(set => set.some(horario2 => conflicts(horario, horario2)));
            if (setIndex === -1) {
                conflictBlocksPacked.push([horario]);
            } else {
                conflictBlocksPacked[setIndex].push(horario);
            }
        })

        classes.forEach(horario =>
            newBlock(horario, <?= $write ?>)
        )

        conflictBlocksPacked.forEach(horarios =>
            newConflictBlock(horarios, <?= $write ?>)
        )

        // remove the elements that are not in the limits
        let max_hour = Math.max(...horarios.map(horario => {
            const lastMoment = moment(horario.hora, "HH:mm").add(horario.bloques * 15, "minutes");
            const lastHour = moment(`${lastMoment.hours()}:00`, "HH:mm");
            const hourInt = parseInt(lastMoment.format("HH"));

            return lastMoment.isSame(lastHour) ? hourInt - 1 : hourInt;
        }));

        let min_hour = Math.min(...horarios.map(horario => parseInt(horario.hora.split(":")[0])));

        document.querySelectorAll("tbody#horario tr").forEach(hora => {
            const hora_id = parseInt(hora.id.split("-")[1].split(":")[0]);
            (hora_id < min_hour || hora_id > max_hour) ? hora.remove(): null;
        })

        // if there is no sábado, remove the column
        if (!horarios.some(horario => horario.dia == "sábado")) {
            document.querySelectorAll("tbody#horario td").forEach(td => {
                if (td.id.split("-")[2] == "sábado") {
                    td.remove();
                }
            });

            // remove the header (the last)
            document.querySelector("#headers").lastElementChild.remove();
        }
        // adjust width
        const ths = document.querySelectorAll("tr#headers th");
        ths.forEach((th, key) =>
            th.style.width = (key == 0) ? "5%" : `${95 / (ths.length - 1)}%`
        );

        // search item animation
        const menúFlontantes = document.querySelectorAll(".menu-flotante");
        menúFlontantes.forEach((element) => {
            element.classList.add("d-none");
            element.parentElement.addEventListener("mouseover", () =>
                element.classList.remove("d-none")
            );
            element.parentElement.addEventListener("mouseout", (e) =>
                element.classList.add("d-none")
            );
        });

    } catch (error) {
        triggerMessage("Error al cargar el horario", "Error");
        triggerMessage(error, "Error");
    }

    // droppables
    // forall the .bloque-elements add the event listeners for drag and drop
    <?php if ($write) : ?>
        document.querySelectorAll(".bloque-clase").forEach(element => {
            function dragStart() {
                this.classList.add("dragging");
            }

            function dragEnd() {
                this.classList.remove("dragging");
            }

            element.addEventListener("dragstart", dragStart);
            element.addEventListener("dragend", dragEnd);
        });

        // forall the cells that are not .bloque-clase add the event listeners for drag and drop
        document.querySelectorAll("td:not(.bloque-clase)").forEach(element => {
            function dragOver(e) {
                e.preventDefault();
                this.classList.add("dragging-over");
            }

            function dragLeave() {
                this.classList.remove("dragging-over");
            }

            function drop() {
                this.classList.remove("dragging-over");
                const dragging = document.querySelector(".dragging");

                const id = /* for data-ids */ dragging.getAttribute("data-ids");
                const hora = /* for data-hora */ this.id.split("-")[1];
                const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
                let día = /* for data-dia */ this.id.split("-")[2];
                día = días.indexOf(día) + 1;

                //  rowspan
                const bloques = parseInt(dragging.getAttribute("rowspan"));
                const horaMoment = moment(hora, "HH:mm");
                const horaFin = horaMoment.add(bloques * 15, "minutes");

                const limit = moment('22:00', 'HH:mm');

                if (horaFin.isAfter(limit)) {
                    triggerMessage("No se puede mover el bloque a esa hora", "Error");

                    // scroll to the top
                    window.scrollTo(0, 0);
                    return;
                }


                moveHorario(id, día, hora);
            }

            element.addEventListener("dragover", dragOver);
            element.addEventListener("dragleave", dragLeave);
            element.addEventListener("drop", drop);
        });
    <?php endif; ?>

    // Remove loading animation in the button
    btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
    btn.disabled = false;

    // console.table(gHorarios);
}

async function guardar(id) {
    const btn = document.querySelector("#btn-guardar");
    const clone = btn.cloneNode(true);
    btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
    btn.disabled = true;

    const data = {
        dia: document.querySelector("#editor_dia"),
        salon: document.querySelector("#editor_salón"),
        //vprofesor: document.querySelector("#editor_profesor"),
        duración: document.querySelector("#editor_duración")
    };

    const dia = data.dia.value;
    const salon = data.salon.value;

    if (salon == "") {
        btn.innerHTML = clone.innerHTML;
        btn.disabled = false;
        return;
    }

    const hora = document.querySelector("#selector_horas").value;
    const minutos = document.querySelector("#selector_minutos").value;
    const bloques = document.querySelector("#dlduración li.selected").getAttribute("data-bloques");

    const start = moment(`${hora}:${minutos}`, "HH:mm").add(bloques * 15, "minutes");
    const end = moment("22:00", "HH:mm");

    if (start.isAfter(end)) {
        btn.innerHTML = clone.innerHTML;
        btn.disabled = false;
        document.querySelector("#dlduración").classList.add("is-invalid");
        return;
    }

    const profesoresList = [...document.querySelectorAll("#profesores li")];

    if (profesoresList.length == 0) {
        btn.innerHTML = clone.innerHTML;
        btn.disabled = false;
        return;
    }

    const formData = new FormData();
    // const id = btn.getAttribute("data-id");
    formData.append("id", id);
    const horas = document.querySelectorAll("#selector_horas, #selector_minutos")
    formData.append("hora", `${horas[0].value}:${horas[1].value}`);
    formData.append("día", dia);
    formData.append("salón", salon);
    const profesores = profesoresList.map(li => li.getAttribute("data-id"));
    formData.append("duración", data.duración.value);
    formData.append("profesores", profesores.join(","));


    const response = await fetch("action/action_horario_update.php", {
        method: "POST",
        body: formData
    }).then(res => res.json());

    if (response.status == "success") {
        triggerMessage("Horario actualizado", "Éxito", "success");
        btn.innerHTML = '<i class="ing-aceptar ing"></i> Guardado';
        btn.classList.add("btn-success");
        btn.classList.remove("btn-primary");

        // return to the initial state
        setTimeout(() => {
            buscarGrupo();
            btn.replaceWith(clone);
            $("#modal-editar").modal("hide");
        }, 100);
    } else {
        triggerMessage(response.message, "Error");
        btn.replaceWith(clone);

        $("#modal-editar").modal("hide");
    }

}
async function borrarHorario(id) {
    const btn = document.querySelector("#btn-borrar");
    const clone = btn.cloneNode(true);
    btn.innerHTML = '<i class="ing-cargando ing"></i> Borrando...';
    btn.disabled = true;

    const formData = new FormData();
    formData.append("id", id);

    const response = await fetch("action/action_horario_delete.php", {
        method: "POST",
        body: formData
    }).then(res => res.json());

    if (response.status == "success") {
        triggerMessage('Horario borrado', "Éxito", "success");
        btn.innerHTML = '<i class="ing-aceptar ing"></i> Borrado';
        btn.classList.add("btn-success");
        btn.classList.remove("btn-danger");

        // return to the initial state
        setTimeout(() => {
            buscarGrupo();
            btn.replaceWith(clone);
            $("#modal-borrar").modal("hide");
        }, 1000);
    } else {
        triggerMessage(response.message, "Error");
        btn.replaceWith(clone);

        $("#modal-borrar").modal("hide");
    }

}

function guardarHorario() {
    let goBack = false;
    const btn = document.querySelector("#btn-guardar-horario");
    const clone = btn.cloneNode(true);
    btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
    btn.disabled = true;

    const data = {
        dia: document.querySelector("#new_dia"),
        salon: document.querySelector("#new_salón"),
        profesor: document.querySelector("#new_profesor"),
        duración: document.querySelector("#new_duración"),
        materia: document.querySelector("#new_materia")
    };

    const dia = data.dia.value;
    const salon = data.salon.value;
    const profesor = data.profesor.value;
    const materia = data.materia.value;
    const duración = data.duración.value;

    if (duración == "") {
        invalidDatalist("#new_duración");
        goBack = true;
    }

    if (profesor == "") {
        data.profesor.classList.add("is-invalid");
        goBack = true;
    }

    if (salon == "") {
        data.salon.classList.add("is-invalid");
        goBack = true;
    }

    if (dia == "") {
        invalidDatalist("#new_dia");
        goBack = true;
    }

    if (materia == "") {
        data.materia.classList.add("is-invalid");
        goBack = true;
    }

    const hora = document.querySelector("#new_horas").value;
    if (hora == "") {
        invalidDatalist("#new_horas");
        goBack = true;
    }
    const minutos = document.querySelector("#new_minutos").value;
    if (minutos == "") {
        invalidDatalist("#new_minutos");
        goBack = true;
    }

    const bloques = document.querySelector("#dlNewDuración li.selected")?.getAttribute("data-bloques");
    const start = moment(`${hora}:${minutos}`, "HH:mm").add(bloques * 15, "minutes");
    const end = moment("22:00", "HH:mm");

    if (start.isAfter(end)) {
        document.querySelector("#dlNewDuración").classList.add("is-invalid");
        goBack = true;
    }

    if (goBack) {
        btn.innerHTML = clone.innerHTML;
        btn.disabled = false;
        return;
    }

    const formData = new FormData();
    formData.append("grupo", document.querySelector("#filter_grupo").value);
    formData.append("hora", `${hora}:${minutos}`);
    formData.append("día", dia);
    formData.append("salón", salon);
    formData.append("profesor", profesor);
    formData.append("duración", data.duración.value);
    formData.append("periodo", "<?= $user->periodo_id ?>");
    formData.append("materia", materia);
    formData.append("facultad", "<?= $user->facultad['facultad_id'] ?>");


    fetch("action/action_horario_create.php", {
        method: "POST",
        body: formData
    }).then(res => res.json()).then(response => {
        if (response.status == "success") {
            triggerMessage("Horario guardado", "Éxito", "success");
            btn.innerHTML = /* html */ `<i class="ing-aceptar ing"></i> Guardado`;
            btn.classList.add("btn-success");
            btn.classList.remove("btn-primary");

            // return to the initial state
            setTimeout(() => {
                btn.innerHTML = clone.innerHTML;
                btn.disabled = false;
                btn.classList.remove("btn-success");
                btn.classList.add("btn-primary");


                // this modal
                $("#modal-nuevo").modal("hide");
                const modalNuevo = document.querySelector("#modal-nuevo");
                modalNuevo.querySelectorAll("input").forEach(input => {
                    input.value = "";
                });

                // reset the datalist
                modalNuevo.querySelectorAll(".datalist").forEach(datalist => {
                    const cloneDatalist = modalNuevoClone.querySelector(`#${datalist.id}`).cloneNode(true);
                    // log
                    datalist.replaceWith(cloneDatalist);
                });
                // remove all is-valid and is-invalid
                modalNuevo.querySelectorAll(".is-valid, .is-invalid").forEach(el => {
                    el.classList.remove("is-valid", "is-invalid");
                });

            }, 100);
        } else {
            triggerMessage(response.message, "Error");
            btn.innerHTML = clone.innerHTML;
            btn.disabled = false;


            $("#modal-nuevo").modal("hide");
        }
    }).then(() => {
        buscarGrupo();
    }).catch(err => {
        triggerMessage(err, "Error");
        btn.innerHTML = clone.innerHTML;
        btn.disabled = false;

        $("#modal-nuevo").modal("hide");
    });

    // buscarGrupo();
}

function moveHorario(id, día, hora) {

    const formData = new FormData();

    formData.append("id", id);
    formData.append("hora", hora);
    formData.append("día", día);

    fetch("action/action_horario_update.php", {
        method: "POST",
        body: formData
    }).then(res => res.json()).then(response => {
        if (response.status == "success") {
            triggerMessage("Horario movido", "Éxito", "success");
        } else {
            triggerMessage(response.message, "Error");
        }
    }).then(() => {
        buscarGrupo();
    }).catch(err => {
        triggerMessage(err, "Error");
    });

}

// initial state
{
    // fill the table with empty cells
    [...Array(16).keys()].map(x => x + 7).forEach(hora => {
        // add 7 rows for each hour
        [0, 15, 30, 45].map(minute => minute.toString().padStart(2, '0')).forEach(minute => {
            const tr = document.createElement("tr");
            tr.id = `hora-${hora}:${minute}`;
            tr.classList.add(hora > 13 ? "tarde" : "mañana");
            if (minute == 0) {
                const th = document.createElement("th");
                th.classList.add("text-center");
                th.scope = "row";
                th.rowSpan = 4;
                th.innerText = `${hora}:00`;
                th.style.verticalAlign = "middle";
                tr.appendChild(th);
            }

            ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].forEach(día => {
                const td = document.createElement("td");
                td.id = `hora-${hora}:${minute}-${día}`;
                tr.appendChild(td);
            });
            document.querySelector("tbody#horario").appendChild(tr);
        });
    })

    // add an inital height to the table cells
    // query selector All tds and ths inside the tbody#horario
    // previous query selector: "tbody#horario td, tbody#horario tr"
    document.querySelectorAll("tbody#horario td, tbody#horario tr").forEach(element => element.style.height = "2rem");
    document.getElementById('btn-buscar').addEventListener('click', buscarGrupo);
    document.getElementById('dlProfesor').addEventListener('input', function(e) {
        var input = document.getElementById('dlProfesor');
        var value = input.value;
        var option = document.querySelector(`option[value="${value}"]`);

        if (!option) {
            document.getElementById('editor_profesor').value = "";
            // remove is valid class
            input.classList.remove("is-valid");
            // add is invalid class
            input.classList.add("is-invalid");
            return
        }

        var id = option.getAttribute('data-id');
        if (!document.querySelector(`li[data-id="${id}"]`))
            listProfesor({
                id: id,
                grado: option.getAttribute('data-grado'),
                profesor: option.getAttribute('data-profesor'),
                clave: option.getAttribute('data-clave')
            });
        e.target.value = "";
    });
}

// state
const table = document.querySelector("table");
const empty_table = table.innerHTML;
document.querySelectorAll('.hidden').forEach(element => element.style.display = "none");
// hide the table
table.style.display = "none";
disableDatalist("#filter_grupo");

document.getElementById("btn-excel-horario").addEventListener("click", () => {
    const formData = new FormData();
    const grupo = document.getElementById("filter_grupo").value;
    formData.append("grupo", grupo);
    formData.append('sábado', gHorarios.some(horario => horario.dia == "sábado"));
    formData.append("horarios", JSON.stringify(gHorarios));
    // min and max hour
    formData.append("min", gHorarios.reduce((min, horario) => {
        const hora = horario.hora.split(":").map(x => parseInt(x))[0]
        return Math.min(hora, min);
    }, 24));
    formData.append("max", gHorarios.reduce((max, horario) => {
        const {
            hora,
            bloques
        } = horario;
        // after hour
        const lastHour = moment(hora, "HH:mm").add(bloques * 15, "minutes");
        const lastMoment = moment(`${lastHour.format("HH")}:00`, "HH:mm");
        const intHour = parseInt(lastHour.format("HH"));

        return Math.max(lastMoment.isSame(lastHour) ? intHour - 1 : intHour, max);
    }, 0));

    fetch("export/horario_excel.php", {
            method: "POST",
            body: formData
        })
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.setAttribute('href', url);
            a.setAttribute('download', `horario-${grupo}.xlsx`);
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        })
        .catch(() => triggerMessage("error", "Error al exportar el horario"));
});

// on click the li element, inside datalist #dlcarera
document.querySelectorAll("#dlcarrera li").forEach(async li => {
    li.addEventListener("click", async () => {
        // get the data-id from the li element
        const carrera = li.getAttribute("data-id");
        const facultad = '<?= $user->facultad['facultad_id'] ?>';
        const periodo = '<?= $user->periodo_id ?>';

        const formData = new FormData();
        formData.append("carrera", carrera);
        formData.append("facultad", facultad);
        formData.append("periodo", periodo);

        try {
            const {
                status,
                grupos
            } = await fetch("action/action_grupo.php", {
                method: "POST",
                body: formData
            }).then(res => res.json());

            if (status != "success") {
                throw new Error("Error al cargar los grupos");
            } else if (grupos.length == 0) {
                throw new Error("No hay grupos para esta carrera");
            }

            const dlgrupo = document.querySelector("#dlgrupo ul");
            const prompt = document.querySelector("#dlgrupo .datalist-input");
            dlgrupo.innerHTML = "";

            grupos.forEach(grupo => {
                const li = document.createElement("li");
                // data-id is the id of the group
                li.setAttribute("data-id", grupo);
                li.textContent = grupo;
                dlgrupo.appendChild(li);
            });

            // write Seleccionar grupo
            prompt.textContent = "Seleccionar grupo";

            disableDatalist("#filter_grupo", false);

            // to #filter_grupo input value
            const filter_grupo = document.querySelector("#filter_grupo");
            filter_grupo.value = "";
        } catch (error) {
            // remove Error: from the error message
            error = error.toString().replace("Error: ", "");
            triggerMessage(error, "Error");
            console.error(error);
        }

        const datalist = document.querySelector("#materias");
        const materias = await fetch("action/action_materias.php", {
            method: "POST",
            body: formData
        }).then(res => res.json());
    });

})

// on modal edit, show the data
$("#modal-editar").on("show.bs.modal", async function(event) {
    document.querySelectorAll("#modal-editar .is-invalid, #modal-editar .is-valid")?.forEach(element => element.classList.remove("is-invalid", "is-valid"));

    const button = event.relatedTarget;
    const parentId = button.parentElement.parentElement.getAttribute("data-ids");

    const {
        id,
        dia,
        hora,
        materia,
        salon,
        profesores,
        duracion
    } = gHorarios?.find(horario => horario.id == parentId);

    // search the data-id of the day and click it
    const númeroDía = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'].reduce((acc, curr, key) => (curr == dia) ? key : acc);
    document.querySelector(`#dldia li[data-id="${númeroDía}"]`)?.click();
    document.querySelector(`#dlduración li[data-id="${duracion}"]`)?.click();
    const horas = hora.split(":")[0];
    const minutos = hora.split(":")[1];

    setDatalist("#selector_horas", horas);
    setDatalist("#selector_minutos", minutos);
    document.getElementById('editor_salón').value = salon;


    // get the option with data-id profesor
    document.getElementById("profesores").innerHTML = "";
    profesores.forEach(listProfesor);

    const btnGuardar = document.getElementById('btn-guardar');
    btnGuardar.onclick = () => guardar(id);
})

$("#modal-borrar").modal({
    show: false,
    backdrop: "static",
    keyboard: false,
})

$("#modal-borrar").on("show.bs.modal", async function(event) {
    const button = event.relatedTarget;
    const id = button.parentElement.parentElement.getAttribute("data-ids");

    const btnBorrar = document.getElementById('btn-borrar');
    btnBorrar.onclick = () => borrarHorario(id);
})