import {useState, useMemo, useEffect, useContext} from "react";
import styles from "./Calendar.module.css";
import {formatDateLetterJS} from "../../../../utils/date/formatDateLetter.js";
import {AuthContext} from "../../../../contexts/Auth/AuthContext.ts";
import ExportBtn from "../../../../components/ExportCalendarBtn/ExportBtn.tsx";

function
Calendar() {
    const { user } = useContext(AuthContext);

    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, setCurrentYear] = useState(today.getFullYear());
    const [selectedDay, setSelectedDay] = useState(null);

    const eventsByDate = useMemo(() => {
        if (!user?.tasks) return {};
        return user.tasks.reduce((eventsByDate, task) => {
            if (!task?.start) return eventsByDate;
            const dateKey = task.start.split(" ")[0];
            if (!eventsByDate[dateKey]) eventsByDate[dateKey] = [];
            eventsByDate[dateKey].push(task);
            return eventsByDate;
        }, {});
    }, [user]);

    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={() => {
                            if (currentMonth === 0) {
                                setCurrentMonth(11);
                                setCurrentYear(y => y - 1);
                            } else {
                                setCurrentMonth(m => m - 1);
                            }
                        }}
                    >
                        ◀
                    </button>
                    <p>{monthNames[currentMonth]} {currentYear}</p>
                    <button
                        onClick={() => {
                            if (currentMonth === 11) {
                                setCurrentMonth(0);
                                setCurrentYear(y => y + 1);
                            } else {
                                setCurrentMonth(m => 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(event => (
                                    <li key={event.id}>
                                        <strong>{event.name}</strong><br/>
                                        - {event.description}
                                    </li>
                                ))}
                            </ul>
                        ) : (
                            <p>Aucun événement ce jour-là.</p>
                        )}
                    </div>
                )}
                <div className={styles.exportbox}>
                    <ExportBtn />
                </div>
            </div>
        </div>
    );
}

export default Calendar;