import { useMemo, useContext } from "react";
import styles from "./EventList.module.css";
import EventItem from "./EventItem";
import { EventContext } from "../../../../contexts/Events/EventContext";

type Task = {
  name: string;
  description: string;
  start: string | Date;
  end: string | Date;
};

type EventGroup = {
  date: string;
  name: string;
  start: string | Date;
  tasks: Task[];
};

type EventContextType = {
  events?: EventGroup[];
};

function EventList() {
  const { events = [] } = useContext(EventContext) as EventContextType;

  const sortedEvents = useMemo<EventGroup[]>(() => {
    if (!Array.isArray(events)) return [];

    return [...events].sort(
      (a, b) =>
        new Date(a.start).getTime() - new Date(b.start).getTime()
    );
  }, [events]);

  return (
    <div className={`${styles.glassCard} glassCard`}>
      <h2>Liste des événements à venir</h2>

      {sortedEvents.length > 0 ? (
        <div className={styles.eventList}>
          {sortedEvents.map((eventGroup, index) => (
            <EventItem eventGroup={eventGroup} key={index} />
          ))}
        </div>
      ) : (
        <p>Aucun événement planifié pour l'instant.</p>
      )}
    </div>
  );
}

export default EventList;