import React, { useState, useEffect } from 'react';
import './MyCalendar.css';

export default function MyCalendar({ onDaySelect, selectedDateRange, onClearSelection }) {
    // Initialiser le calendrier à la date actuelle par défaut si aucune date n'est en cours
    
    const [currentDate, setCurrentDate] = useState(new Date()); 
    
    const today = new Date();
    today.setHours(0, 0, 0, 0); 

    const [publicHolidays, setPublicHolidays] = useState({});

    const weekdays = ['D', 'L', 'Ma', 'Me', 'J', 'V', 'S'];
    const monthNames = [
        "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
        "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
    ];

    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();

    useEffect(() => {
        const fetchPublicHolidays = async (yearToFetch) => {
            try {
                const response = await fetch(`https://calendrier.api.gouv.fr/jours-feries/metropole/${yearToFetch}.json`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();
                setPublicHolidays(data);
            } catch (error) {
                console.error("Erreur lors de la récupération des jours fériés :", error);
                setPublicHolidays({});
            }
        };

        fetchPublicHolidays(year);
    }, [year]);

    const isPublicHoliday = (day) => {
        if (day === null) return false;
        const dateString = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        return publicHolidays.hasOwnProperty(dateString);
    };

    const firstDayOfMonth = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();

    const calendarDays = [];
    for (let i = 0; i < firstDayOfMonth; i++) {
        calendarDays.push(null);
    }
    for (let i = 1; i <= daysInMonth; i++) {
        calendarDays.push(i);
    }

    const handlePrevMonth = () => {
        setCurrentDate(prevDate => {
            const newDate = new Date(prevDate);
            newDate.setMonth(newDate.getMonth() - 1);
            // Empêche de revenir avant le mois actuel si aujourd'hui est dans ce mois
           
            if (newDate.getFullYear() < today.getFullYear() || (newDate.getFullYear() === today.getFullYear() && newDate.getMonth() < today.getMonth())) {
                return prevDate; // Reste sur le mois actuel
            }
            return newDate;
        });
        if (onClearSelection) onClearSelection();
    };

    const handleNextMonth = () => {
        setCurrentDate(prevDate => {
            const newDate = new Date(prevDate);
            newDate.setMonth(newDate.getMonth() + 1);
            return newDate;
        });
        if (onClearSelection) onClearSelection();
    };

   
    const isPastDay = (day) => {
        if (day === null) return false;
        const currentDay = new Date(year, month, day);
        currentDay.setHours(0, 0, 0, 0); 

        if (year < today.getFullYear()) return true;
        if (year === today.getFullYear() && month < today.getMonth()) return true;

      
        if (year === today.getFullYear() && month === today.getMonth() && day < today.getDate()) {
            return true;
        }

        return false;
    };

   
    const isToday = (day) => {
        if (day === null) return false;
        return day === today.getDate() && month === today.getMonth() && year === today.getFullYear();
    };

    const handleDayClick = (day) => {
        if (day === null || isPastDay(day)) return; 

        const clickedDate = new Date(year, month, day);
        if (onDaySelect) {
            onDaySelect(clickedDate);
        }
    };

    const isDayInSelectedRange = (day) => {
        if (day === null || selectedDateRange.length === 0) return false;

        const currentDayDate = new Date(year, month, day);
        currentDayDate.setHours(0, 0, 0, 0);

        const start = selectedDateRange[0] instanceof Date ? new Date(selectedDateRange[0].getFullYear(), selectedDateRange[0].getMonth(), selectedDateRange[0].getDate()) : null;
        const end = selectedDateRange[1] instanceof Date ? new Date(selectedDateRange[1].getFullYear(), selectedDateRange[1].getMonth(), selectedDateRange[1].getDate()) : null;

        if (start) start.setHours(0, 0, 0, 0);
        if (end) end.setHours(0, 0, 0, 0);

        if (selectedDateRange.length === 1) {
            return start && currentDayDate.getTime() === start.getTime();
        } else if (selectedDateRange.length === 2) {
            return start && end && currentDayDate.getTime() >= start.getTime() && currentDayDate.getTime() <= end.getTime();
        }
        return false;
    };

    return (
        <div className="my-calendar-section">
            <h2 className="section-title">Mon calendrier</h2>
            <div className="calendar-header">
                
                <span
                    className={`calendar-nav ${year < today.getFullYear() || (year === today.getFullYear() && month <= today.getMonth()) ? 'disabled' : ''}`}
                    onClick={year < today.getFullYear() || (year === today.getFullYear() && month <= today.getMonth()) ? null : handlePrevMonth}
                >
                    &lt;
                </span>
                <span className="calendar-month-year">
                    {monthNames[month]} {year}
                </span>
                <span className="calendar-nav" onClick={handleNextMonth}>&gt;</span>
            </div>
            <div className="calendar-grid">
                {weekdays.map((day, index) => (
                    <div key={index} className="calendar-weekday">{day}</div>
                ))}
                {calendarDays.map((day, index) => {
                    const holidayInfo = isPublicHoliday(day) ? publicHolidays[`${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`] : '';
                    const past = isPastDay(day);
                    const todayClass = isToday(day);
                    const isInRange = isDayInSelectedRange(day);

                    return (
                        <div
                            key={index}
                            className={`calendar-day 
                                ${day === null ? 'empty' : ''} 
                                ${holidayInfo ? 'public-holiday' : ''}
                                ${past ? 'past-day' : ''} {/* Ajout de la classe pour les jours passés */}
                                ${todayClass ? 'today' : ''} {/* Ajout de la classe pour aujourd'hui */}
                                ${isInRange ? 'selected-range' : ''}
                            `}
                            onClick={past ? null : () => handleDayClick(day)} 
                        >
                            {day}
                            {holidayInfo && <div className="holiday-label">{holidayInfo}</div>}
                        </div>
                    );
                })}
            </div>
        </div>
    );
}