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

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const eventId = urlParams.get('event');

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

    var container   = document.getElementById("mainContainer");
    const modifyBtn = document.getElementById("editBtn");
    const removeBtn = document.getElementById("removeBtn");
    const applyBtn = document.getElementById("applyBtn");
    var org_id: number = -1;

    try {
        var user = await getMyAccount();
        if (user) {
            if (user.isOrganisation) {
                org_id = user.organisationId;
            }
            unhideElementById(document, "logout-btn");
        }
    } catch {
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }

    var thisEvent = null;
    try {
        if (eventId) thisEvent = await getEvent(eventId);
    } catch (err) {
        if (container !== null) container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powr�t -></a></p>`;
    }

    if (thisEvent == null) {
        if (container !== null) container.innerHTML = `<p class="text-danger">Błąd we wczytywaniu wydarzenia. <a href="/" style="color:#2898BD;">Powrót -></a></p>`;
    } else {

        const titleText     = document.getElementById(    "titleText") as HTMLElement;
        const locationText  = document.getElementById( "locationText") as HTMLElement;
        const descText      = document.getElementById(     "descText") as HTMLElement;
        const dateText      = document.getElementById(     "dateText") as HTMLElement;
        const organizerText = document.getElementById("organizerText") as HTMLElement;
        const newdateText   = new Date(thisEvent.eventDate).toLocaleDateString('pl-PL');
        const newtimeText   = new Date(thisEvent.eventDate).toLocaleTimeString('pl-PL');


            titleText.innerHTML = thisEvent.title + ` (#${eventId})`;
         locationText.innerHTML = "Place: " + thisEvent.location;
             descText.innerHTML = thisEvent.description;
             dateText.innerHTML = "When: " + newdateText + " " + newtimeText; //thisEvent.eventDate;
        organizerText.innerHTML = "Organized by: " + thisEvent.organisationName;

        if (org_id == thisEvent.organisationId) {
            // Użytkownik jest organizacją, która
            // stworzyła to wydarzenie
            unhideElementById(document, "editBtn");
            unhideElementById(document, "removeBtn");
        } else if (org_id == -1) {
            // Użytkownik jest wolontariuszem
            const registeredIds = await getMyRegisteredEventIds();
            const isRegistered = registeredIds.includes(Number(eventId));

            if (isRegistered) {
                unhideElementById(document, "leaveBtn");
            } else {
                unhideElementById(document, "applyBtn");
            }
        }

        unhideElementById(document, "mainContainer");

    }

    if (modifyBtn) {
        modifyBtn.addEventListener("click", (e) => {
            window.location.href = "/modify.html?event=" + eventId;
        });
    }

    if (removeBtn) {
        removeBtn.addEventListener("click", async (e) => {
            const confirmed = confirm("Really delete?");
            if (!confirmed) return;

            try {
                // Wysyła żądanie DELETE do API
                const response = await fetch(`/api/events/${eventId}`, {
                    method: "DELETE"
                });

                if (response.ok) {
                    alert("Event deleted.");
                    window.location.href = "/";
                } else {
                    alert("Couldn't delete event.");
                }
            } catch (err) {
                alert("Couldn't connect.");
                console.error(err);
            }
        });
    }

    if (applyBtn) {
        applyBtn.addEventListener("click", async (e) => {
            try {
                const response = await fetch(`/api/events/join/${eventId}`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                });

                const result: {
                    success: boolean;
                    error_msg?: string;
                } = await response.json();

                if (result.success) {
                    (applyBtn as HTMLButtonElement).disabled = true;
                    (applyBtn as HTMLButtonElement).textContent = "Applied Succesfully";
                } else {
                    alert(`Error: ${result.error_msg ?? "Unknown error occurred."}`);
                }
            } catch (error) {
                console.error("Failed to apply:", error);
                alert("Failed to apply due to a network or server error.");
            }
        });
    }

});
