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

var isAscending: boolean = false;
var optionsVisibility: boolean = false;

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

function toggleOptionsVisibility() {
    optionsVisibility = !optionsVisibility;
    if (optionsVisibility) {
        unhideElementById(document, "fDate");
        unhideElementById(document, "tDate");
        unhideElementById(document, "flabel");
        unhideElementById(document, "tlabel");
    } else {
        hideElementById(document, "fDate");
        hideElementById(document, "tDate");
        hideElementById(document, "flabel");
        hideElementById(document, "tlabel");
    }
}

async function getEvents(titleOrDescription?: string, fDate?: Date, tDate?: Date) {

    var res: Response;
    var searchbar = document.getElementById("searchbar") as HTMLInputElement;
    var eventDateFrom = (document.getElementById('fDate') as HTMLInputElement).value;
    var eventDateTo = (document.getElementById('tDate') as HTMLInputElement).value;

    if (titleOrDescription == null) {
        titleOrDescription = searchbar.value;
    }

    if (optionsVisibility) {
        var payload_visible = {
            titleOrDescription,
            eventDateFrom,
            eventDateTo
        };
        res = await fetch('/api/events/search' + (isAscending ? "?sort=asc" : ""), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload_visible)
        });
        if (!res.ok) throw new Error("Failed to get search results");
    } else {
        var payload_invisible = {
            titleOrDescription
        };
        res = await fetch('/api/events/search' + (isAscending ? "?sort=asc" : ""), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload_invisible)
        });
        if (!res.ok) throw new Error("Failed to get search results");
    }

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

async function sendMessageForEvent(eventId: number) {
    const messageContent = `Help me with <a href="/view.html?event=${eventId}">this event</a>`;

    try {
        const response = await fetch('/api/messages/sendFromOrgToVolunteers', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ eventId, content: messageContent })
        });

        if (response.ok) {
            alert('Message sent successfully to all volunteers!');
        } else {
            let error = await response.text();
            if (!error) error = `Status code: ${response.status}`;
            alert('Failed to send message: ' + error);
            console.error('Send message failed', response.status, error);
        }
    } catch (error) {
        alert('Error sending message: ' + error);
        console.error('Fetch error:', error);
    }
}

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'>No events to display at this moment.</p>";
            return;
        }

        container.innerHTML = '';

        for (const ev of events) {
            const card = document.createElement("div");
            card.className = "event-card filled";

            let formattedDate: string = new Intl.DateTimeFormat('en-US', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            }).format(new Date(ev.eventDate));

            const eventInfoSpan = document.createElement("span");
            eventInfoSpan.innerHTML = `
                <a href="/view.html?event=${ev.eventId}" style="color: #2898BD">${ev.title}</a>
                <p style="margin: 0">👥 ${ev.organisation} | 📍 ${ev.location} | 📅 ${formattedDate}</p>
            `;
            card.appendChild(eventInfoSpan);

            if (org_id == ev.organisationId) {
                const buttonsDiv = document.createElement("div");
                buttonsDiv.className = "d-flex gap-2 mt-2";

                const editBtn = document.createElement("button");
                editBtn.className = "edit-btn mod-btn";
                editBtn.setAttribute("data-id", ev.eventId);
                editBtn.title = "Edit event";
                editBtn.innerHTML = `<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>`;

                const removeBtn = document.createElement("button");
                removeBtn.className = "remove-btn mod-btn";
                removeBtn.setAttribute("data-id", ev.eventId);
                removeBtn.title = "Remove event";
                removeBtn.innerHTML = `<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>`;

                const sendMsgBtn = document.createElement("button");
                sendMsgBtn.className = "btn btn-sm btn-info";
                sendMsgBtn.textContent = "Send Message";
                sendMsgBtn.setAttribute("data-id", ev.eventId);
                sendMsgBtn.title = "Send message about this event";
                sendMsgBtn.addEventListener("click", async () => {
                    await sendMessageForEvent(ev.eventId);
                });

                buttonsDiv.appendChild(editBtn);
                buttonsDiv.appendChild(removeBtn);
                buttonsDiv.appendChild(sendMsgBtn);

                card.appendChild(buttonsDiv);
            }

            container.appendChild(card);
        }
    } catch (err) {
        container.innerHTML = `<p class="text-danger">General failure when trying to load data.</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 {
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }

    loadEvents(org_id);

    const listSortToggleButton = document.getElementById("list-sort-btn");
    if (listSortToggleButton) {
        listSortToggleButton.addEventListener("click", () => toggleListSortOrder(org_id));
    }

    const optionsToggleButton = document.getElementById("optionsbtn");
    if (optionsToggleButton) {
        optionsToggleButton.addEventListener("click", () => toggleOptionsVisibility());
    }

    const searchBar = document.getElementById('searchbar') as HTMLInputElement;
    searchBar.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            var searchResults = getEvents(searchBar.value);
            loadEvents(org_id, searchResults);
        }
    });
});
