const createTh = (value) => {
    const th = document.createElement("th");
    th.setAttribute("scope", "row");
    th.innerText = value;
    return th;
};
const createTd = (value) => {
    const td = document.createElement("td");
    td.innerText = value;
    return td;
};
const createButton = (text, type, action) => {
    const btn = document.createElement("button");
    btn.setAttribute("type", "button");
    btn.classList.add("btn", type);
    btn.innerHTML = text;
    btn.addEventListener("click", action);
    const td = document.createElement("td");
    td.appendChild(btn);
    return td;
};

const studentTable = (tableId, editCallback, deleteCallback) => {
    const draw = async (data) => {
        const students = document.getElementById(tableId);
        students.innerHTML = "";

        data.forEach((element) => {
            const container = document.createElement("tr");
            container.classList.add("align-middle");
            container.appendChild(createTh(element.id));
            container.appendChild(createTd(element.last_name));
            container.appendChild(createTd(element.first_name));
            container.appendChild(createTd(element.bdate));
            container.appendChild(createTd(element.email));
            container.appendChild(createTd(element.phone));
            container.appendChild(createTd(element.group.name));
            container.appendChild(
                createButton("Edit", "btn-warning", async () => {
                    if (editCallback) {
                        editCallback(element);
                    }
                })
            );
            container.appendChild(
                createButton("Delete", "btn-danger", async () => {
                    if (deleteCallback) {
                        deleteCallback(element.id);
                    }
                })
            );
            students.appendChild(container);
        });
    };

    return { draw };
};

export default studentTable;
