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, schedules } =
    usePlanning();

  const getScheduleColor = (event) => {
    const schedule = schedules?.find(
      (item) => Number(item.id) === Number(event.planning)
    );
    return schedule?.color || event.color || '#6B7280';
  };

  const getScheduleClassLevelLabel = (event) => {
    const schedule = schedules?.find(
      (item) => Number(item.id) === Number(event.planning)
    );
    const scheduleName = schedule?.name || '';
    if (!scheduleName) return '';
    return scheduleName;
  };

  // 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-primary/5' : ''}
          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-primary text-white' : ''}
            ${!isCurrentMonth ? 'text-gray-400' : ''}`}
          >
            {format(day, 'd')}
          </span>
        </div>
        <div className="space-y-1 flex-1">
          {dayEvents.map((event) => {
            const scheduleColor = getScheduleColor(event);
            const classLevelLabel = getScheduleClassLevelLabel(event);
            return (
              <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);
              }}
            >
                {classLevelLabel && (
                  <div
                    className="-mx-1 -mt-1 mb-1 px-1 py-0.5 border-t-2"
                    style={{
                      borderTopColor: scheduleColor,
                      backgroundColor: `${scheduleColor}22`,
                    }}
                  >
                    <span
                      className="text-[10px] font-semibold uppercase tracking-wide truncate block text-center"
                      style={{ color: scheduleColor }}
                    >
                      {classLevelLabel}
                    </span>
                  </div>
                )}
              <span className="inline-flex items-center gap-1 max-w-full">
                <span
                  className="w-2 h-2 rounded-full shrink-0"
                  style={{ backgroundColor: event.color }}
                />
                <span className="truncate flex-1">{event.title}</span>
              </span>
            </div>
            );
          })}
        </div>
      </div>
    );
  };

  const dayLabels = [
    { short: 'L', long: 'Lun' },
    { short: 'M', long: 'Mar' },
    { short: 'M', long: 'Mer' },
    { short: 'J', long: 'Jeu' },
    { short: 'V', long: 'Ven' },
    { short: 'S', long: 'Sam' },
    { short: 'D', long: 'Dim' },
  ];

  return (
    <div className="h-full flex flex-col border border-gray-200 rounded-lg bg-white overflow-x-auto">
      <div className="min-w-[280px]">
        {/* En-tête des jours de la semaine */}
        <div className="grid grid-cols-7 border-b">
          {dayLabels.map((day, i) => (
            <div
              key={i}
              className="p-1 sm:p-2 text-center text-xs sm:text-sm font-medium text-gray-500"
            >
              <span className="sm:hidden">{day.short}</span>
              <span className="hidden sm:inline">{day.long}</span>
            </div>
          ))}
        </div>
        {/* Grille des jours */}
        <div className="grid grid-cols-7 grid-rows-[repeat(6,1fr)]">
          {days.map((day) => renderDay(day))}
        </div>
      </div>
    </div>
  );
};

export default MonthView;
