import React from 'react';
import { format, isSameDay, eachDayOfInterval } from 'date-fns';
import { fr } from 'date-fns/locale';

const PlanningView = ({ events, onEventClick }) => {
  // Fonction pour diviser un événement en jours
  const splitEventByDays = (event) => {
    const start = new Date(event.start);
    const end = new Date(event.end);

    // Si même jour, retourner l'événement tel quel
    if (isSameDay(start, end)) {
      return [event];
    }

    // Sinon, créer une entrée pour chaque jour
    const days = eachDayOfInterval({ start, end });
    return days.map((day) => ({
      ...event,
      displayDate: day,
      isMultiDay: true,
    }));
  };

  // Aplatir tous les événements en incluant les événements sur plusieurs jours
  const flattenedEvents = events
    .flatMap(splitEventByDays)
    .sort(
      (a, b) =>
        new Date(a.displayDate || a.start) - new Date(b.displayDate || b.start)
    );

  return (
    <div className="bg-white h-full overflow-auto">
      <table className="min-w-full border-collapse">
        <thead className="bg-gray-50 sticky top-0 z-10">
          <tr>
            <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b">
              Date
            </th>
            <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b">
              Horaires
            </th>
            <th className="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b">
              Événement
            </th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-200">
          {flattenedEvents.map((event, index) => {
            const start = new Date(event.displayDate || event.start);
            const end = new Date(event.end);
            const isMultiDay = event.isMultiDay;

            return (
              <tr
                key={`${event.id}-${index}`}
                className="hover:bg-gray-50 cursor-pointer"
                onClick={() => onEventClick(event)}
              >
                <td className="py-3 px-4 text-sm text-gray-900 whitespace-nowrap">
                  <div className="flex items-center gap-1">
                    <span className="font-extrabold">{format(start, 'd')}</span>
                    <span className="font-semibold">
                      {format(start, 'MMM', { locale: fr }).toLowerCase()}
                    </span>
                    <span className="font-semibold">
                      {format(start, 'EEE', { locale: fr })}
                    </span>
                  </div>
                </td>
                <td className="py-3 px-4 text-sm text-gray-900 whitespace-nowrap">
                  <div className="flex items-center">
                    <div
                      className="w-2 h-2 rounded-full mr-2"
                      style={{ backgroundColor: event.color }}
                    />
                    {isMultiDay
                      ? isSameDay(start, new Date(event.start))
                        ? 'À partir de '
                        : isSameDay(start, end)
                          ? "Jusqu'à "
                          : 'Toute la journée'
                      : ''}
                    {format(new Date(event.start), 'HH:mm')}
                    {!isMultiDay && ` - ${format(end, 'HH:mm')}`}
                  </div>
                </td>
                <td className="py-3 px-4">
                  <div className="flex items-center">
                    <div>
                      <div className="text-sm font-medium text-gray-900">
                        {event.title}
                      </div>
                      {event.description && (
                        <div className="text-sm text-gray-500">
                          {event.description}
                        </div>
                      )}
                      {event.location && (
                        <div className="text-sm text-gray-500">
                          {event.location}
                        </div>
                      )}
                    </div>
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

export default PlanningView;
