'use client';

import { useState, useEffect } from 'react';

interface Trajet {
  id: string;
  date: string;
  adresseDepart: string;
  adresseArrivee: string;
  commentaire?: string | null;
  statut: string;
  adherent: {
    id: string;
    nom: string;
    prenom: string;
    telephone: string;
    email: string;
  };
  chauffeur?: {
    id: string;
    nom: string;
    prenom: string;
    telephone: string;
  } | null;
}

interface CalendrierTrajetsProps {
  refreshTrigger?: number;
}

export default function CalendrierTrajets({ refreshTrigger }: CalendrierTrajetsProps) {
  const [trajets, setTrajets] = useState<Trajet[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [selectedTrajets, setSelectedTrajets] = useState<Trajet[]>([]);

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

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

  // Ajuster pour que lundi soit le premier jour (0 = lundi)
  const adjustedStartingDay = startingDayOfWeek === 0 ? 6 : startingDayOfWeek - 1;

  useEffect(() => {
    fetchTrajets();
  }, [currentDate, refreshTrigger]);

  const fetchTrajets = async () => {
    setLoading(true);
    try {
      const startDate = new Date(year, month, 1).toISOString();
      const endDate = new Date(year, month + 1, 0, 23, 59, 59).toISOString();
      
      const response = await fetch(
        `/api/trajets?startDate=${startDate}&endDate=${endDate}`
      );
      if (response.ok) {
        const data = await response.json();
        setTrajets(data);
      }
    } catch (error) {
      console.error('Erreur lors du chargement des trajets:', error);
    } finally {
      setLoading(false);
    }
  };

  const getTrajetsForDate = (date: Date): Trajet[] => {
    const dateStr = date.toISOString().split('T')[0];
    return trajets.filter((trajet) => {
      const trajetDate = new Date(trajet.date).toISOString().split('T')[0];
      return trajetDate === dateStr;
    });
  };

  const handleDateClick = (date: Date) => {
    setSelectedDate(date);
    const trajetsDuJour = getTrajetsForDate(date);
    setSelectedTrajets(trajetsDuJour);
  };

  const goToPreviousMonth = () => {
    setCurrentDate(new Date(year, month - 1, 1));
  };

  const goToNextMonth = () => {
    setCurrentDate(new Date(year, month + 1, 1));
  };

  const goToToday = () => {
    setCurrentDate(new Date());
  };

  const formatDate = (date: Date) => {
    return date.toLocaleDateString('fr-FR', {
      weekday: 'long',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    });
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
  };

  const days = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
  const calendarDays = [];

  // Ajouter les jours vides du début
  for (let i = 0; i < adjustedStartingDay; i++) {
    calendarDays.push(null);
  }

  // Ajouter les jours du mois
  for (let day = 1; day <= daysInMonth; day++) {
    calendarDays.push(new Date(year, month, day));
  }

  return (
    <div className="bg-white rounded-lg shadow-sm p-6">
      {/* En-tête du calendrier */}
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-semibold text-gray-900">
          {currentDate.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })}
        </h2>
        <div className="flex items-center gap-2">
          <button
            onClick={goToPreviousMonth}
            className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            title="Mois précédent"
          >
            <svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <button
            onClick={goToToday}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            Aujourd'hui
          </button>
          <button
            onClick={goToNextMonth}
            className="p-2 rounded-lg hover:bg-gray-100 transition-colors"
            title="Mois suivant"
          >
            <svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-8 text-gray-500">Chargement...</div>
      ) : (
        <>
          {/* Grille du calendrier */}
          <div className="grid grid-cols-7 gap-2 mb-6">
            {/* En-têtes des jours */}
            {days.map((day) => (
              <div key={day} className="text-center text-sm font-semibold text-gray-600 py-2">
                {day}
              </div>
            ))}

            {/* Jours du calendrier */}
            {calendarDays.map((date, index) => {
              if (!date) {
                return <div key={`empty-${index}`} className="h-24" />;
              }

              const trajetsDuJour = getTrajetsForDate(date);
              const isToday =
                date.getDate() === new Date().getDate() &&
                date.getMonth() === new Date().getMonth() &&
                date.getFullYear() === new Date().getFullYear();
              const isSelected =
                selectedDate &&
                date.getDate() === selectedDate.getDate() &&
                date.getMonth() === selectedDate.getMonth() &&
                date.getFullYear() === selectedDate.getFullYear();

              return (
                <button
                  key={date.toISOString()}
                  onClick={() => handleDateClick(date)}
                  className={`h-24 p-2 rounded-lg border-2 transition-all flex flex-col ${
                    isSelected
                      ? 'border-lblue bg-lblue/10'
                      : isToday
                      ? 'border-lblue bg-lblue/5'
                      : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                  }`}
                >
                  <div className="text-sm font-medium text-gray-900 mb-1">
                    {date.getDate()}
                  </div>
                  {trajetsDuJour.length > 0 && (
                    <div className="space-y-1 flex-1 overflow-hidden">
                      {trajetsDuJour.slice(0, 2).map((trajet) => (
                        <div
                          key={trajet.id}
                          className="text-xs px-1.5 py-0.5 rounded bg-lblue text-white truncate"
                          title={`${trajet.adherent.prenom} ${trajet.adherent.nom} - ${trajet.chauffeur ? `${trajet.chauffeur.prenom} ${trajet.chauffeur.nom}` : 'Sans chauffeur'}`}
                        >
                          {trajet.chauffeur
                            ? `${trajet.chauffeur.prenom.charAt(0)}. ${trajet.chauffeur.nom.charAt(0)}`
                            : 'Sans ch.'}
                        </div>
                      ))}
                      {trajetsDuJour.length > 2 && (
                        <div className="text-xs text-gray-500 font-medium">
                          +{trajetsDuJour.length - 2}
                        </div>
                      )}
                    </div>
                  )}
                </button>
              );
            })}
          </div>

          {/* Détails des trajets du jour sélectionné */}
          {selectedDate && selectedTrajets.length > 0 && (
            <div className="mt-6 pt-6 border-t border-gray-200">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">
                Trajets du {formatDate(selectedDate)}
              </h3>
              <div className="space-y-3">
                {selectedTrajets.map((trajet) => (
                  <div
                    key={trajet.id}
                    className="p-4 bg-gray-50 rounded-lg border border-gray-200"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="text-sm font-semibold text-gray-900">
                            {trajet.adherent.prenom} {trajet.adherent.nom}
                          </span>
                          <span className="px-2 py-0.5 text-xs font-medium rounded bg-lblue/10 text-lblue">
                            {formatTime(trajet.date)}
                          </span>
                          <span
                            className={`px-2 py-0.5 text-xs font-medium rounded ${
                              trajet.statut === 'Terminé'
                                ? 'bg-green-100 text-green-700'
                                : trajet.statut === 'En cours'
                                ? 'bg-blue-100 text-blue-700'
                                : trajet.statut === 'Annulé'
                                ? 'bg-red-100 text-red-700'
                                : 'bg-gray-100 text-gray-700'
                            }`}
                          >
                            {trajet.statut}
                          </span>
                        </div>
                        <div className="text-sm text-gray-600 mb-1">
                          <span className="font-medium">Départ:</span> {trajet.adresseDepart}
                        </div>
                        <div className="text-sm text-gray-600 mb-2">
                          <span className="font-medium">Arrivée:</span> {trajet.adresseArrivee}
                        </div>
                        {trajet.chauffeur ? (
                          <div className="flex items-center gap-2 mt-2">
                            <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17a2 2 0 11-4 0 2 2 0 014 0zM19 17a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                            <span className="text-sm font-medium text-gray-900">
                              Chauffeur: {trajet.chauffeur.prenom} {trajet.chauffeur.nom}
                            </span>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2 mt-2">
                            <svg className="w-4 h-4 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                            </svg>
                            <span className="text-sm text-orange-600 font-medium">
                              Aucun chauffeur assigné
                            </span>
                          </div>
                        )}
                        {trajet.commentaire && (
                          <div className="mt-2 text-sm text-gray-500 italic">
                            {trajet.commentaire}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {selectedDate && selectedTrajets.length === 0 && (
            <div className="mt-6 pt-6 border-t border-gray-200 text-center text-gray-500">
              Aucun trajet prévu pour le {formatDate(selectedDate)}
            </div>
          )}
        </>
      )}
    </div>
  );
}
