import { getEvent, getMyAccount, unhideElementById } from './generalUseHelpers.js';

var isAscending: boolean = false;

function toggleListSortOrder(org_id: number) {
    isAscending = !isAscending;
    loadEvents(org_id);
}

async function getEvents(titleOrDescription?: string) {

    var res: Response;

    if (titleOrDescription == null) {
        res = await fetch("/api/events" + (isAscending ? "?sort=asc" : ""));
        if (!res.ok) throw new Error("Błąd pobierania wydarzeń");
    } else {
        const payload = {
            titleOrDescription
        };
        res = await fetch('/api/events/search', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        if (!res.ok) throw new Error("Błąd wyszukiwania wydarzeń");
    }

    const events = await res.json();
    return events;
}

async function loadEvents(org_id: number, evs?: Promise<any>) {
    const container = document.getElementById("eventList");
    if (!container) return;
    var events: any;

    try {
        if (evs == null) {
            events = await getEvents();
        }
        else {
            events = await evs;
        }

        if (events.length === 0) {
            container.innerHTML = "<p class='text-muted'>Brak wydarzeń do wyświetlenia.</p>";
            return;
        }

        // Wyczyść kontener przed dodaniem nowych
        container.innerHTML = '';

        for (const ev of events) {
            const card = document.createElement("div");
            card.className = "event-card filled";
            //card.innerHTML = `
            //    <span>${ev.title}</span>`
            // Do odkomentowania kiedy widok podglądu wydarzeń będzie gotowy
            card.innerHTML = `
                <span>
                    <a href="/view.html?event=${ev.eventId}" style="color: #2898BD">${ev.title}</a>
                    <p style="margin: 0">${ev.organisation}</p>
                </span>`
            if (org_id == ev.organisationId) {
                card.innerHTML += `
                <div>
                    <button class="edit-btn mod-btn" data-id="${ev.eventId}" id="edit-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#FFFFFF"><path d="M200-200h57l391-391-57-57-391 391v57Zm-80 80v-170l528-527q12-11 26.5-17t30.5-6q16 0 31 6t26 18l55 56q12 11 17.5 26t5.5 30q0 16-5.5 30.5T817-647L290-120H120Zm640-584-56-56 56 56Zm-141 85-28-29 57 57-29-28Z"/></svg>
                    </button>
                    <button class="remove-btn mod-btn" data-id="${ev.eventId}" id="remove-btn">
                        <svg xmlns="http://www.w3.org/2000/svg" height="30px" viewBox="0 -960 960 960" width="30px" fill="#FFFFFF"><path d="M280-440h400v-80H280v80ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>
                    </button>
                </div>`;
            }

            container.appendChild(card);
        }
    } catch (err) {
        container.innerHTML = `<p class="text-danger">Błąd ładowania danych.</p>`;
        console.error(err);
    }
}

document.addEventListener("DOMContentLoaded", async () => {

    var org_id: number = -1;

    try {
        var user = await getMyAccount();

        if (user) {
            if (user.isOrganisation) {
                unhideElementById(document, "mainContainer");
                unhideElementById(document, "addnewevent-btn");
                org_id = user.organisationId;
            }
            unhideElementById(document, "logout-btn");
        }
    } catch {
        // console.log("User not signed in. Failing gracefully.");
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }

    loadEvents(org_id);
    // listen for clicks
    const listSortToggleButton = document.getElementById("list-sort-btn");
    if (listSortToggleButton) {
        listSortToggleButton.addEventListener("click", () => toggleListSortOrder(org_id));
    }
    // and for enter in search bar
    const searchBar = document.getElementById('searchbar') as HTMLInputElement;
    searchBar.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            // console.log('Enter key pressed!');
            var searchResults = getEvents(searchBar.value);
            loadEvents(org_id, searchResults);
        }
    })
});