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

function Calendar() {
    const events = {
        "2025-11-07": ["Réunion de projet", "Anniversaire de Marie"],
        "2025-11-10": ["Cours de React", "Rendez-vous médecin"],
        "2025-11-14": ["Sortie cinéma"],
        "2025-11-15": ["Sortie cinéma"],
        "2025-11-17": ["Sortie cinéma"],
    };
    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(() => {
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        const key = `${year}-${month}-${day}`;
        return {date: key, events: events[key] || []};
    });

    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 handlePrevMonth = () => {
        let newMonth = currentMonth - 1;
        let newYear = currentYear;

        if (newMonth < 0) {
            newMonth = 11;
            newYear--;
        }

        setCurrentMonth(newMonth);
        setCurrentYear(newYear);

        const key = `${newYear}-${String(newMonth + 1).padStart(2, "0")}-01`;
        setSelectedDay({date: key, events: events[key] || []});
    };

    const handleNextMonth = () => {
        let newMonth = currentMonth + 1;
        let newYear = currentYear;

        if (newMonth > 11) {
            newMonth = 0;
            newYear++;
        }

        setCurrentMonth(newMonth);
        setCurrentYear(newYear);

        const key = `${newYear}-${String(newMonth + 1).padStart(2, "0")}-01`;
        setSelectedDay({date: key, events: events[key] || []});
    };

    const handleDayClick = (day) => {
        if (!day) return;
        const key = `${currentYear}-${String(currentMonth + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
        setSelectedDay({date: key, events: events[key] || []});
    };

    return (
        <div className={styles.glassCard}>
            <div className={styles.calendarContainer}>
                <div className={styles.calendarHeader}>
                    <button onClick={handlePrevMonth}>◀</button>
                    <p>{monthNames[currentMonth]} {currentYear}</p>
                    <button onClick={handleNextMonth}>▶</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((_, weekIndex) => (
                        <tr key={weekIndex}>
                            {days.slice(weekIndex * 7, weekIndex * 7 + 7).map((day, index) => {
                                const key = `${currentYear}-${String(currentMonth + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
                                const hasEvent = events[key];

                                return (
                                    <td
                                        key={index}
                                        className={[
                                            day === today.getDate() &&
                                            currentMonth === today.getMonth() &&
                                            currentYear === today.getFullYear()
                                                ? styles.today : "",
                                            hasEvent ? styles.hasEvent : "",
                                            selectedDay?.date === key ? styles.selected : ""
                                        ].join(" ")}
                                        onClick={() => handleDayClick(day)}
                                    >
                                        {day || ""}
                                    </td>
                                );
                            })}
                        </tr>
                    ))}
                    </tbody>
                </table>

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

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

export default Calendar;