import React, { useState, useEffect } from "react";
import styles from "./IncompleteEvent.module.css";
import getAllEvents from "../../utils/events/getAllEvents";

function IncompleteEvent() {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchEvents = async () => {
      const data = await getAllEvents();
      setEvents(data?.data || data || []);
      setLoading(false);
    };
    fetchEvents();
  }, []);

  if (loading) {
    return (
      <div className={`${styles.rightBlock} glassCard`}>
        <h2>Derniers événements</h2>
        <div className={styles.eventsContainer}>
          <div className={`${styles.emptyEvent} glassCard`}>
            <p>Chargement des événements...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`${styles.rightBlock} glassCard`}>
      <h2>Derniers événements</h2>
      <div className={styles.eventsContainer}>
        {events.map((event) => (
          <div key={event.id} className={`glassCard ${styles.eventCard}`}>
            <h3>{event.name}</h3>
            <p className={styles.eventDate}>
              {new Date(event.start).toLocaleDateString("fr-FR")} - {new Date(event.end).toLocaleDateString("fr-FR")}
            </p>
            <p className={styles.eventDescription}>{event.description}</p>
            <h4>Tâches associées :</h4>
            <ul className={styles.tasksList}>
              {event.tasks?.length ? (
                event.tasks.map((task, taskIndex) => (
                  <li key={taskIndex}>{task.name}</li>
                ))
              ) : (
                <li>Aucune tâche associée.</li>
              )}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}

export default IncompleteEvent;
