import { getApiUrls, getClosestIndicator } from "./dom.mjs";
import { getCsrfToken } from "./utils.mjs";
import { fetchPost } from "./utils.mjs";

async function updateLeftMenu() {
    const parts = window.location.pathname.split("/").filter(Boolean);
    const theme_name = parts[parts.length - 1];
    const comparison = parts.includes("comparaison");
    const response = await fetch(
        `/api/website/left-menu/${theme_name}/?comparison=${comparison}`,
    );
    if (response.ok) {
        const htmlData = await response.text();
        const leftMenu = document.getElementById("left-menu");
        leftMenu.innerHTML = htmlData;
    }
}

function removeIndicatorCardFromFavoritePage(data, indicator) {
    if (isFavoritePage() && data.isFavorite === false) {
        const card = document.getElementById(`card-${indicator.id}`);
        if (card) {
            card.remove();
        }
        if (document.querySelector(".indicator-card") === null) {
            const section = document.getElementById("tableau-de-bord");
            if (section) {
                const empty = document.createElement("div");
                empty.className = "empty-favorite";
                empty.textContent =
                    "Vous n'avez pas d'indicateurs favoris dans votre tableau de bord.";
                section.appendChild(empty);
            }
        }
    }
}

async function toggleFavorite(button) {
    const indicator = getClosestIndicator(button);
    const apiUrls = getApiUrls(indicator);
    button.setAttribute("disabled", "true");
    try {
        const response = await fetchPost(apiUrls["favorite"], {
            indicator_id: indicator.id,
        });
        if (response.ok) {
            const data = await response.json();
            button.parentElement.innerHTML = data.html;
            removeIndicatorCardFromFavoritePage(data, indicator);
            if (data.updateLeftMenu) updateLeftMenu();
        }
    } finally {
        try {
            button.removeAttribute("disabled");
        } finally {
        }
    }
}

function isFavoritePage() {
    return window.location.pathname === "/indicateurs/favoris/";
}

function disableExtremumArrows() {
    const topArrow = document.querySelector(".card-order-up");
    topArrow.disabled = true;
    const arrows = document.querySelectorAll(".card-order-down");
    if (arrows.length > 0) {
        const bottomArrow = arrows[arrows.length - 1];
        bottomArrow.disabled = true;
    }
}

function refreshArrows() {
    document
        .querySelectorAll(".card-order-up, .card-order-down")
        .forEach((btn) => {
            btn.disabled = false;
        });
    disableExtremumArrows();
}

function swapTwoElements(el1, el2) {
    const placeholder = document.createTextNode("");
    el1.after(placeholder);
    el2.after(el1);
    placeholder.replaceWith(el2);
}

function animatedSwap(el1, el2) {
    const top1 = el1.getBoundingClientRect().top;
    const top2 = el2.getBoundingClientRect().top;
    swapTwoElements(el1, el2);
    const newTop1 = el1.getBoundingClientRect().top;
    const newTop2 = el2.getBoundingClientRect().top;
    const options = { duration: 400, easing: "ease-in-out" };
    el1.animate(
        [
            { transform: `translateY(${top1 - newTop1}px)` },
            { transform: "translateY(0)" },
        ],
        options,
    );
    el2.animate(
        [
            { transform: `translateY(${top2 - newTop2}px)` },
            { transform: "translateY(0)" },
        ],
        options,
    );
}

async function orderFavorite(button) {
    const isUp = button.classList.contains("card-order-up");
    const thisCard = button.closest(".indicator-card");
    const cardToSwap = isUp
        ? thisCard.previousElementSibling
        : thisCard.nextElementSibling;
    if (!cardToSwap) return;

    animatedSwap(thisCard, cardToSwap);
    refreshArrows();

    const indicator = getClosestIndicator(thisCard);
    const apiUrls = getApiUrls(indicator);
    fetchPost(apiUrls["favorite-order"], {
        indicator_id: indicator.id,
        direction: isUp ? "up" : "down",
    });
}

if (isFavoritePage()) {
    document.addEventListener("DOMContentLoaded", () => {
        disableExtremumArrows();
    });
}

export { toggleFavorite, orderFavorite };
