import React from 'react';
import { usePlanning } from '@/context/PlanningContext';
import { format, startOfWeek, endOfWeek, eachDayOfInterval, startOfMonth, endOfMonth, isSameMonth, isToday } from 'date-fns';
import { fr } from 'date-fns/locale';
import { getEventsForDate } from '@/utils/events';

const MonthView = ({ onDateClick, onEventClick }) => {
  const { currentDate, setViewType, setCurrentDate, events } = usePlanning();

  // Obtenir tous les jours du mois actuel
  const monthStart = startOfMonth(currentDate);
  const monthEnd = endOfMonth(currentDate);
  const startDate = startOfWeek(monthStart, { locale: fr, weekStartsOn: 1 });
  const endDate = endOfWeek(monthEnd, { locale: fr, weekStartsOn: 1 });

  const days = eachDayOfInterval({ start: startDate, end: endDate });

  const handleDayClick = (day) => {
    setCurrentDate(day); // Met à jour la date courante
    setViewType('week'); // Change la vue en mode semaine
  };

  const renderDay = (day) => {
    const isCurrentMonth = isSameMonth(day, currentDate);
    const dayEvents = getEventsForDate(day, events);
    const isCurrentDay = isToday(day);

    return (
      <div
        key={day.toString()}
        className={`p-2 overflow-y-auto relative flex flex-col
          ${!isCurrentMonth ? 'bg-gray-100 text-gray-400' : ''}
          ${isCurrentDay ? 'bg-emerald-50' : ''}
          hover:bg-gray-100 cursor-pointer border-b border-r`}
        onClick={() => handleDayClick(day)}
      >
        <div className="flex justify-between items-center mb-1">
          <span className={`text-sm font-medium rounded-full w-7 h-7 flex items-center justify-center
            ${isCurrentDay ? 'bg-emerald-500 text-white' : ''}
            ${!isCurrentMonth ? 'text-gray-400' : ''}`}
          >
            {format(day, 'd')}
          </span>
        </div>
        <div className="space-y-1 flex-1">
          {dayEvents.map((event, index) => (
            <div
              key={event.id}
              className="text-xs p-1 rounded truncate cursor-pointer"
              style={{
                backgroundColor: `${event.color}15`,
                color: event.color,
                borderLeft: `2px solid ${event.color}`
              }}
              onClick={(e) => {
                e.stopPropagation();
                onEventClick(event);
              }}
            >
              {event.title}
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="h-full flex flex-col border border-gray-200 rounded-lg bg-white">
      {/* En-tête des jours de la semaine */}
      <div className="grid grid-cols-7 border-b">
        {['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'].map(day => (
          <div key={day} className="p-2 text-center text-sm font-medium text-gray-500">
            {day}
          </div>
        ))}
      </div>
      {/* Grille des jours */}
      <div className="flex-1 grid grid-cols-7 grid-rows-[repeat(6,1fr)]">
        {days.map((day) => renderDay(day))}
      </div>
    </div>
  );
};

export default MonthView;