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

function Calendar({ events = [] }) {

    const monthNames = [
        "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
        "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
    ];

    const today = new Date();

    const [currentMonth, setCurrentMonth] = useState(today.getMonth());
    const [currentYear] = useState(today.getFullYear());
    const [selectedDay, setSelectedDay] = useState(null);

    const eventsByDate = useMemo(() => {
        return events.reduce((acc, ev) => {
            if (!ev?.start) return acc;

            const dateKey = ev.start.split(" ")[0]; // YYYY-MM-DD
            if (!acc[dateKey]) acc[dateKey] = [];
            acc[dateKey].push(ev);
            return acc;
        }, {});
    }, [events]);

    useEffect(() => {
        const key = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

        setSelectedDay({
            date: key,
            events: eventsByDate[key] || []
        });
    }, [eventsByDate]);

    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const firstDay = new Date(currentYear, currentMonth, 1).getDay();
    const startDay = (firstDay + 6) % 7;

    const days = [];
    for (let i = 0; i < startDay; i++) days.push(null);
    for (let i = 1; i <= daysInMonth; i++) days.push(i);

    const selectDay = (year, month, day) => {
        const key = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
        setSelectedDay({
            date: key,
            events: eventsByDate[key] || []
        });
    };

    const handleDayClick = (day) => {
        if (!day) return;
        selectDay(currentYear, currentMonth, day);
    };

    return (
        <div className={`${styles.glassCard} glassCard`}>
            <div className={styles.calendarContainer}>

                <div className={styles.calendarHeader}>
                    <button onClick={() => setCurrentMonth(m => m === 0 ? 11 : m - 1)}>◀</button>
                    <p>{monthNames[currentMonth]} {currentYear}</p>
                    <button onClick={() => setCurrentMonth(m => m === 11 ? 0 : m + 1)}>▶</button>
                </div>

                <table className={styles.calendar}>
                    <thead>
                    <tr>
                        <th>Lun</th><th>Mar</th><th>Mer</th>
                        <th>Jeu</th><th>Ven</th><th>Sam</th><th>Dim</th>
                    </tr>
                    </thead>
                    <tbody>
                    {Array.from({ length: Math.ceil(days.length / 7) }).map((_, w) => (
                        <tr key={w}>
                            {days.slice(w * 7, w * 7 + 7).map((day, i) => {
                                if (!day) return <td key={i}></td>;

                                const key = `${currentYear}-${String(currentMonth + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
                                const hasEvent = (eventsByDate[key]?.length ?? 0) > 0;

                                return (
                                    <td
                                        key={i}
                                        className={[
                                            hasEvent ? styles.hasEvent : "",
                                            selectedDay?.date === key ? styles.selected : ""
                                        ].join(" ")}
                                        onClick={() => handleDayClick(day)}
                                    >
                                        {day}
                                    </td>
                                );
                            })}
                        </tr>
                    ))}
                    </tbody>
                </table>

                {selectedDay && (
                    <div className={`${styles.eventBox} glassBorder`}>
                        <h3>Événements du {formatDateLetterJS(selectedDay.date)}</h3>

                        {selectedDay.events.length > 0 ? (
                            <ul>
                                {selectedDay.events.map(ev => (
                                    <li key={ev.id}>
                                        <strong>{ev.name}</strong><br />
                                        {ev.description}
                                    </li>
                                ))}
                            </ul>
                        ) : (
                            <p>Aucun événement ce jour-là.</p>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}

export default Calendar;