import { useMemo, useEffect, useState } from "react";
import styles from "./eventList.module.css";
import formatDateLetter from "../../utils/date/formatDateLetter.js";
import getAllEvents from "../../utils/event/getAllEvents.js";


function EventList() {

    const [events, setEvents] = useState([]);

    useEffect(() => {
        (async () => {
            const data = await getAllEvents();
            setEvents(data.data);
            console.log(data.data);
        }) ()
    }, [])

    const sortedEvents = useMemo(() => {
        return [...events].sort(
            (a, b) => new Date(a.start) - new Date(b.start)
        );
    }, [events]);


    return (
        <div className={styles.glassCard}>
                <h2>Liste des événements à venir</h2>
                {sortedEvents.length > 0 ? (
                    <ul className={styles.eventList}>
                        {sortedEvents.map((eventGroup, index) => (

                            <li key={index} className={styles.eventGroup}>
                                <div className={styles.eventTitle}>
                                    <p className={styles.title}>{eventGroup.name}</p>
                                    <p>{formatDateLetter(eventGroup.start)} - {formatDateLetter(eventGroup.end)}</p>
                                </div>
                                <ul className={styles.eventDetails}>
                                    {eventGroup.tasks.map((task, i) => (
                                        <li key={i} className={styles.eventTasks}>
                                            <p>- {task.name} - {task.description}</p>
                                            <p>{formatDateLetter(task.start)} - {formatDateLetter(task.end)}</p>
                                        </li>
                                    ))}
                                </ul>
                            </li>

                        ))}
                    </ul>
                ) : (
                    <p>Aucun événement planifié pour l'instant.</p>
                )}
        </div>

    );
}

export default EventList;