const toggleButton = document.getElementById("toggle_button")
const navLinks = document.getElementById("navsite_list")

toggleButton.addEventListener('click', () => {
    navLinks.classList.toggle("active")
})


let UserInfo;

function handleResponse(data, successMessage, failureMessage) {
    const statusMessageContainer = document.getElementById("statusMessageContainer");

    const statusMessage = document.createElement("div");
    statusMessage.classList.add("status-message");

    if (data.Status === 'Success') {
        statusMessage.innerText = successMessage;
        statusMessage.classList.add("success");
    } else {
        statusMessage.innerText = failureMessage;
        statusMessage.classList.add("failure");
    }

    statusMessageContainer.appendChild(statusMessage);

    // Automatically remove the message after 3 seconds
    setTimeout(() => {
        statusMessage.style.opacity = "0";
        setTimeout(() => {
            statusMessage.remove();
        }, 500);
    }, 3000);
}

async function doAction(url, requestData, successMessage, failureMessage, silent = false) {
    try {
        const params = new URLSearchParams();

        for (const key in requestData) {
            params.append(key, requestData[key]);
        }

        const response = await fetch(url, {
            method: 'POST',
            body: params,
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();

        if (!silent) {
            handleResponse(data, successMessage, failureMessage);
        }

        return data;
    } catch (error) {
        console.error('Error:', error);
    }
}

function handlePageResponse(data) {
    const navbar = document.getElementById("navbar");
    const pageArea = document.getElementById("pagearea");

    if (data.Navigation) {
        navbar.innerHTML = data.Navigation;
    }

    if (data.Page) {
        pageArea.innerHTML = data.Page;
        if(data.PageLocation){
            history.pushState({}, "", data.PageLocation);
        }
    }
}

function displayList(data, elementId, deleteFunction) {
    const tableContainer = document.getElementById(elementId);
    tableContainer.innerHTML = ""; // Clear previous content

    const table = document.createElement("table");
    table.classList.add("list-table");

    const headerRow = table.insertRow(0);
    for (const key in data[0]) {
        const th = document.createElement("th");
        th.appendChild(document.createTextNode(key));
        headerRow.appendChild(th);
    }

    if (typeof deleteFunction === "function") {
        const th = document.createElement("th");
        th.appendChild(document.createTextNode("Delete"));
        headerRow.appendChild(th);
    }

    for (const line of data) {
        const dataRow = table.insertRow();
        for (const key in line) {
            const td = document.createElement("td");
            td.appendChild(document.createTextNode(line[key]));
            dataRow.appendChild(td);
        }
        if (typeof deleteFunction === "function") {
            const td = document.createElement("td");
            const deleteButton = document.createElement('button');
            deleteButton.textContent = "Delete";
            deleteButton.onclick = () => deleteFunction(line.ID);
            td.appendChild(deleteButton);
            dataRow.appendChild(td);
        }
    }

    tableContainer.appendChild(table);
}

async function doPageAction(requestData, wantsReturn = false) {
    try {
        const response = await fetch('/page', {
            method: 'POST',
            body: new URLSearchParams(requestData),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();
        handlePageResponse(data);
        if (wantsReturn) {
            return data;
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

function initAjax() {
    const links = document.querySelectorAll('.navsite_link, .navpage_link');

    links.forEach(function (link) {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            let site = this.dataset.site;
            let page = this.dataset.page;
            if (site && page) {
                navigateTo(site, page);
            }
        });
    });
    onPageLoad();
}

document.addEventListener('DOMContentLoaded', initAjax);

function onPageLoad(){
    let currentSite = localStorage.getItem("currentSite");
    let currentPage = localStorage.getItem("currentPage");
    if(currentSite === "home" && currentPage === "settings"){
        if(document.getElementById("user-settings")){
            getUserInfo();
        }
        if(document.getElementById("admin-settings")){
            listActivationCodes();
            listUsers();
        }
    }
}

function navigateTo(site, page){
    const data = {
        action: "getPage",
        site: site,
        page: page,
    };
    doPageAction(data, true).then(() => {
        localStorage.setItem("currentSite", site);
        localStorage.setItem("currentPage", page);
        onPageLoad();
    });
}

function softReload(){
    let currentSite = localStorage.getItem("currentSite");
    let currentPage = localStorage.getItem("currentPage");
    navigateTo(currentSite, currentPage);
    umami.track("softReload");
}

function refreshNavbar(){
    const data = {
        action: "getNavigation",
    };
    doPageAction(data);
    umami.track("refreshNavbar");
}

function logout() {
    const data = {
        action: "logout",
    };

    doAction('/account', data, "Logout Successful!", "Logout failed.").then(() => {
        refreshNavbar();
        navigateTo("", localStorage.getItem("defaultPage"));
        umami.track("logout");
    });
}

function login() {
    const email = document.getElementById("login_email").value;
    const password = document.getElementById("login_password").value;
    doLogin(email, password);
    refreshNavbar();
    softReload();
}

async function doLogin(email, password) {
    const data = {
        action: "login",
        email: email,
        password: password,
    };

    await doAction('/account', data, "Login Successful!", "Login failed. Please check your credentials.");
    umami.track("login");
}

function register() {
    const firstName = document.getElementById("register_firstName").value;
    const lastName = document.getElementById("register_lastName").value;
    const email = document.getElementById("register_email").value;
    const password = document.getElementById("register_password").value;
    const activationToken = document.getElementById("register_activationToken").value;

    const data = {
        action: "register",
        firstname: firstName,
        lastname: lastName,
        email: email,
        password: password,
        activation_token: activationToken,
    };

    doRegister(data);
}

async function doRegister(requestData) {
    await doAction('/account', requestData, "Registration Successful!", "Registration failed.");
    umami.track("register");
}

//User settings start

function changePassword() {
    const oldPassword = document.getElementById("changeOldPassword").value;
    const newPassword = document.getElementById("changeNewPassword").value;

    const data = {
        action: "change_password",
        old_password: oldPassword,
        new_password: newPassword,
    };

    doChangePassword(data, "Password change Successful!", "Password change failed.");
}

async function doChangePassword(requestData, successMessage, failureMessage) {
    await doAction('/account', requestData, successMessage, failureMessage);
    umami.track("passwordChange");
}

function updateUserProfile() {
    const firstName = document.getElementById("updateFirstName").value;
    const lastName = document.getElementById("updateLastName").value;
    const nickname = document.getElementById("updateNickname").value;
    const minecraftNick = document.getElementById("updateMinecraftNick").value;

    const data = {
        action: "update_user_profile",
        first_name: firstName,
        last_name: lastName,
        nickname: nickname,
        minecraft_nick: minecraftNick,
    };

    doAction('/account', data, "Profile update Successful!", "Profile update failed.");
    umami.track("updateUserProfile");
}

function updateEmail() {
    const newEmail = document.getElementById("updateNewEmail").value;

    const data = {
        action: "update_user_email",
        email: newEmail,
    };

    doAction('/account', data, "Email update Successful!", "Email update failed.");
    umami.track("updateEmail");
}

function populateUserInfoFields(userData) {
    document.getElementById("updateFirstName").value = userData.FirstName || "";
    document.getElementById("updateLastName").value = userData.LastName || "";
    document.getElementById("updateNickname").value = userData.Nickname || "";
    document.getElementById("updateMinecraftNick").value = userData.MinecraftNick || "";
    document.getElementById("updateNewEmail").value = userData.Email || "";
}

function getUserInfo() {
    const data = {
        action: "get_user_info",
    };

    const result = doAction('/account', data, "User info retrieved Successfully!", "User info retrieval failed.", true);

    if (result && result.Status === "Success") {
        populateUserInfoFields(result.UserInfo);
        UserInfo = result.UserInfo;
    }
}

//User settings end

//Admin settings start

function addActivationCodes() {
    const count = document.getElementById("activationCodeCount").value;

    const data = {
        action: "add_activation_codes",
        count: count,
    };

    const result = doAction('/account', data, "Activation codes added Successfully!", "Activation codes addition failed.");

    displayList(result.ActivationCodes, "codeListTable", deleteActivationCode);
    umami.track("addActivationCodes");
}

function listUsers() {
    const data = {
        action: "list_users",
    };

    const result = doAction('/account', data, "User list retrieved Successfully!", "User list retrieval failed.");

    if (result && result.Status === "Success") {
        displayList(result.Users, "userListTable", deleteUser);
    }
}

function listActivationCodes() {
    const data = {
        action: "list_activation_codes",
    };

    const result = doAction('/account', data, "Activation code list retrieved Successfully!", "Activation code list retrieval failed.");

    displayList(result.ActivationCodes, "codeListTable", deleteActivationCode);
}

function deleteUser(userId) {
    const data = {
        action: "delete_user",
        user_id: userId,
    };

    doAction('/account', data, "User deleted Successfully!", "User deletion failed.");
    listUsers();
    umami.track("deleteUser");
}

function deleteActivationCode(activationCode) {
    const data = {
        action: "delete_activation_code",
        activation_code: activationCode,
    };

    doAction('/account', data, "Activation code deleted Successfully!", "Activation code deletion failed.");
    listActivationCodes();
    umami.track("deleteActivationCode");
}
//Admin settings end
