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

async function createEvent() {
    // Pobieranie danych z formularza
    const title = (document.getElementById('title') as HTMLInputElement).value;
    const location = (document.getElementById('location') as HTMLInputElement).value;
    const description = (document.getElementById('description') as HTMLTextAreaElement).value;
    const eventDateRaw = (document.getElementById('eventDate') as HTMLInputElement).value;

    // Walidacja prostych pól
    if (!title || !location || !eventDateRaw) {
        alert("Please fill out all of the required fields!");
        return;
    }

    const eventDate = new Date(eventDateRaw).toISOString();

    const payload = {
        title,
        location,
        description,
        eventDate,
    };

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

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText);
        }

        alert("Event created successfully!");
        window.location.href = "/"; // Przekierowanie do strony głównej
    } catch (error) {
        console.error("Couldn't create event:", error);
        alert("Couldn't create new event: " + error);
    }
}

document.addEventListener("DOMContentLoaded", async () => {
    const saveBtn = document.getElementById("saveBtn");

    var user = await getMyAccount();
    if (user) {
        if (user.isOrganisation) {
            unhideElementById(document, "mainContainer");
        }
        unhideElementById(document, "logout-btn");
    } else {
        unhideElementById(document, "joinnow-btn");
        unhideElementById(document, "signin-btn");
    }

    if (saveBtn) {
        saveBtn.addEventListener("click", (e) => {
            e.preventDefault();
            createEvent();
        });
    }
});