'use client';

import { useState, useEffect, useRef } from 'react';
import TrajetMap from './TrajetMap';
import AddressAutocomplete from './AddressAutocomplete';

interface Adherent {
  id: string;
  nom: string;
  prenom: string;
  adresse: string;
  telephone: string;
  email: string;
}

interface Chauffeur {
  id: string;
  nom: string;
  prenom: string;
  telephone: string;
  email: string;
}

interface TrajetFormProps {
  onClose: () => void;
  onSuccess: () => void;
  trajetToEdit?: {
    id: string;
    date: string;
    adresseDepart: string;
    adresseArrivee: string;
    commentaire?: string | null;
    statut: string;
    adherentId: string;
    chauffeurId?: string | null;
  };
}

export default function TrajetForm({ onClose, onSuccess, trajetToEdit }: TrajetFormProps) {
  const [loading, setLoading] = useState(false);
  const [adherents, setAdherents] = useState<Adherent[]>([]);
  const [chauffeurs, setChauffeurs] = useState<Chauffeur[]>([]);
  const [searchAdherent, setSearchAdherent] = useState('');
  const [searchChauffeur, setSearchChauffeur] = useState('');
  const [showAdherentDropdown, setShowAdherentDropdown] = useState(false);
  const [showChauffeurDropdown, setShowChauffeurDropdown] = useState(false);
  const adherentDropdownRef = useRef<HTMLDivElement>(null);
  const chauffeurDropdownRef = useRef<HTMLDivElement>(null);

  const [formData, setFormData] = useState({
    adherentId: trajetToEdit?.adherentId || '',
    adherentNom: '',
    adherentPrenom: '',
    adherentAdresse: '',
    adherentTelephone: '',
    chauffeurId: trajetToEdit?.chauffeurId || '',
    chauffeurNom: '',
    chauffeurPrenom: '',
    chauffeurTelephone: '',
    date: trajetToEdit ? new Date(trajetToEdit.date).toISOString().split('T')[0] : '',
    heure: trajetToEdit ? new Date(trajetToEdit.date).toTimeString().slice(0, 5) : '',
    adresseDepart: trajetToEdit?.adresseDepart || '',
    adresseArrivee: trajetToEdit?.adresseArrivee || '',
    commentaire: trajetToEdit?.commentaire || '',
  });

  useEffect(() => {
    fetchAdherents();
    fetchChauffeurs();
  }, []);

  useEffect(() => {
    // Si on modifie un trajet, charger les données de l'adhérent et du chauffeur
    if (trajetToEdit) {
      if (trajetToEdit.adherentId) {
        fetch(`/api/adherents/${trajetToEdit.adherentId}`)
          .then(res => res.json())
          .then(data => {
            if (data) {
              setFormData(prev => ({
                ...prev,
                adherentId: data.id,
                adherentNom: data.nom,
                adherentPrenom: data.prenom,
                adherentAdresse: data.adresse,
                adherentTelephone: data.telephone,
                adresseDepart: data.adresse,
              }));
              setSearchAdherent(`${data.prenom} ${data.nom}`);
            }
          })
          .catch(console.error);
      }
      
      if (trajetToEdit.chauffeurId) {
        fetch(`/api/chauffeurs/${trajetToEdit.chauffeurId}`)
          .then(res => res.json())
          .then(data => {
            if (data) {
              setFormData(prev => ({
                ...prev,
                chauffeurId: data.id,
                chauffeurNom: data.nom,
                chauffeurPrenom: data.prenom,
                chauffeurTelephone: data.telephone,
              }));
              setSearchChauffeur(`${data.prenom} ${data.nom}`);
            }
          })
          .catch(console.error);
      }
    }
  }, [trajetToEdit]);

  // Fermer les dropdowns quand on clique en dehors
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        adherentDropdownRef.current &&
        !adherentDropdownRef.current.contains(event.target as Node)
      ) {
        setShowAdherentDropdown(false);
      }
      if (
        chauffeurDropdownRef.current &&
        !chauffeurDropdownRef.current.contains(event.target as Node)
      ) {
        setShowChauffeurDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const fetchAdherents = async () => {
    try {
      const response = await fetch('/api/adherents');
      if (response.ok) {
        const data = await response.json();
        setAdherents(data);
      }
    } catch (error) {
      console.error('Erreur lors du chargement des adhérents:', error);
    }
  };

  const fetchChauffeurs = async () => {
    try {
      const response = await fetch('/api/chauffeurs');
      if (response.ok) {
        const data = await response.json();
        setChauffeurs(data);
      }
    } catch (error) {
      console.error('Erreur lors du chargement des chauffeurs:', error);
    }
  };

  const handleSelectAdherent = (adherent: Adherent) => {
    setFormData({
      ...formData,
      adherentId: adherent.id,
      adherentNom: adherent.nom,
      adherentPrenom: adherent.prenom,
      adherentAdresse: adherent.adresse,
      adherentTelephone: adherent.telephone,
      adresseDepart: adherent.adresse, // Remplir automatiquement l'adresse de départ
    });
    setSearchAdherent(`${adherent.prenom} ${adherent.nom}`);
    setShowAdherentDropdown(false);
  };

  const handleSelectChauffeur = (chauffeur: Chauffeur) => {
    setFormData({
      ...formData,
      chauffeurId: chauffeur.id,
      chauffeurNom: chauffeur.nom,
      chauffeurPrenom: chauffeur.prenom,
      chauffeurTelephone: chauffeur.telephone,
    });
    setSearchChauffeur(`${chauffeur.prenom} ${chauffeur.nom}`);
    setShowChauffeurDropdown(false);
  };

  const filteredAdherents = adherents.filter(
    (a) =>
      !searchAdherent ||
      `${a.prenom} ${a.nom}`.toLowerCase().includes(searchAdherent.toLowerCase()) ||
      a.email.toLowerCase().includes(searchAdherent.toLowerCase()) ||
      a.telephone.includes(searchAdherent)
  );

  const filteredChauffeurs = chauffeurs.filter(
    (c) =>
      !searchChauffeur ||
      `${c.prenom} ${c.nom}`.toLowerCase().includes(searchChauffeur.toLowerCase()) ||
      c.email.toLowerCase().includes(searchChauffeur.toLowerCase()) ||
      c.telephone.includes(searchChauffeur)
  );

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      // Combiner date et heure
      const dateTime = formData.date && formData.heure
        ? new Date(`${formData.date}T${formData.heure}`).toISOString()
        : formData.date
        ? new Date(`${formData.date}T09:00`).toISOString()
        : new Date().toISOString();

      const url = trajetToEdit ? `/api/trajets/${trajetToEdit.id}` : '/api/trajets';
      const method = trajetToEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          date: dateTime,
          adresseDepart: formData.adresseDepart,
          adresseArrivee: formData.adresseArrivee,
          commentaire: formData.commentaire || null,
          statut: trajetToEdit?.statut || 'Planifié',
          adherentId: formData.adherentId,
          chauffeurId: formData.chauffeurId || null,
        }),
      });

      if (response.ok) {
        onSuccess();
        onClose();
      } else {
        const error = await response.json();
        alert(`Erreur: ${error.error || `Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet`}`);
      }
    } catch (error) {
      console.error(`Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet:`, error);
      alert(`Erreur lors de la ${trajetToEdit ? 'modification' : 'création'} du trajet`);
    } finally {
      setLoading(false);
    }
  };

  const getInitials = (nom: string, prenom: string) => {
    return `${prenom.charAt(0)}${nom.charAt(0)}`.toUpperCase();
  };

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fadeIn">
      <div className="bg-white rounded-lg shadow-xl max-w-7xl w-full max-h-[95vh] overflow-hidden flex flex-col animate-slideUp border border-gray-200">
        {/* Header */}
        <div className="border-b border-gray-200 px-6 py-5 bg-white">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-2xl font-semibold text-gray-900">
                {trajetToEdit ? 'Modifier le trajet' : 'Nouveau trajet'}
              </h2>
              <p className="text-sm text-gray-500 mt-1">
                {trajetToEdit ? 'Modifiez les informations du trajet' : 'Créez un nouveau trajet pour un adhérent'}
              </p>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors p-2 hover:bg-gray-100 rounded-lg"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        {/* Content */}
        <form id="trajet-form" onSubmit={handleSubmit} className="flex-1 overflow-hidden flex">
          {/* Colonne gauche - Formulaire */}
          <div className="flex-1 overflow-y-auto px-8 py-8 border-r border-gray-200">
            <div className="space-y-6">
              {/* Sélection adhérent */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  Adhérent <span className="text-red-500">*</span>
                </label>
                <div className="relative" ref={adherentDropdownRef}>
                  <input
                    type="text"
                    placeholder="Rechercher un adhérent..."
                    value={searchAdherent}
                    onChange={(e) => {
                      setSearchAdherent(e.target.value);
                      setShowAdherentDropdown(true);
                    }}
                    onFocus={() => setShowAdherentDropdown(true)}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
                  />
                  {showAdherentDropdown && filteredAdherents.length > 0 && (
                    <div className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                      {filteredAdherents.map((adherent) => (
                        <button
                          key={adherent.id}
                          type="button"
                          onClick={() => handleSelectAdherent(adherent)}
                          className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-b-0"
                        >
                          <div className="w-10 h-10 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold text-sm">
                            {getInitials(adherent.nom, adherent.prenom)}
                          </div>
                          <div>
                            <div className="text-sm font-medium text-gray-900">
                              {adherent.prenom} {adherent.nom}
                            </div>
                            <div className="text-xs text-gray-500">{adherent.email}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                {formData.adherentId && (
                  <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold text-sm">
                        {getInitials(formData.adherentNom, formData.adherentPrenom)}
                      </div>
                      <div className="flex-1">
                        <div className="text-sm font-medium text-gray-900">
                          {formData.adherentPrenom} {formData.adherentNom}
                        </div>
                        <div className="text-xs text-gray-500">{formData.adherentTelephone}</div>
                        <div className="text-xs text-gray-500 mt-1">{formData.adherentAdresse}</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Sélection chauffeur */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  Chauffeur
                </label>
                <div className="relative" ref={chauffeurDropdownRef}>
                  <input
                    type="text"
                    placeholder="Rechercher un chauffeur..."
                    value={searchChauffeur}
                    onChange={(e) => {
                      setSearchChauffeur(e.target.value);
                      setShowChauffeurDropdown(true);
                    }}
                    onFocus={() => setShowChauffeurDropdown(true)}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
                  />
                  {showChauffeurDropdown && filteredChauffeurs.length > 0 && (
                    <div className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                      {filteredChauffeurs.map((chauffeur) => (
                        <button
                          key={chauffeur.id}
                          type="button"
                          onClick={() => handleSelectChauffeur(chauffeur)}
                          className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center gap-3 border-b border-gray-100 last:border-b-0"
                        >
                          <div className="w-10 h-10 rounded-full bg-lblue flex items-center justify-center text-white font-semibold text-sm">
                            {getInitials(chauffeur.nom, chauffeur.prenom)}
                          </div>
                          <div>
                            <div className="text-sm font-medium text-gray-900">
                              {chauffeur.prenom} {chauffeur.nom}
                            </div>
                            <div className="text-xs text-gray-500">{chauffeur.email}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
                {formData.chauffeurId && (
                  <div className="mt-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-full bg-lblue flex items-center justify-center text-white font-semibold text-sm">
                        {getInitials(formData.chauffeurNom, formData.chauffeurPrenom)}
                      </div>
                      <div className="flex-1">
                        <div className="text-sm font-medium text-gray-900">
                          {formData.chauffeurPrenom} {formData.chauffeurNom}
                        </div>
                        <div className="text-xs text-gray-500">{formData.chauffeurTelephone}</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Date et heure */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-900 mb-2">
                    Date <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="date"
                    required
                    value={formData.date}
                    onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-900 mb-2">
                    Heure <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="time"
                    required
                    value={formData.heure}
                    onChange={(e) => setFormData({ ...formData, heure: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent"
                  />
                </div>
              </div>

              {/* Adresse de départ */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  Adresse de départ <span className="text-red-500">*</span>
                </label>
                <AddressAutocomplete
                  value={formData.adresseDepart}
                  onChange={(address) => setFormData({ ...formData, adresseDepart: address })}
                  placeholder="Rechercher une adresse de départ..."
                  required
                />
              </div>

              {/* Adresse d'arrivée */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  Adresse d'arrivée <span className="text-red-500">*</span>
                </label>
                <AddressAutocomplete
                  value={formData.adresseArrivee}
                  onChange={(address) => setFormData({ ...formData, adresseArrivee: address })}
                  placeholder="Rechercher une adresse d'arrivée..."
                  required
                />
              </div>

              {/* Commentaire */}
              <div>
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  Commentaire
                </label>
                <textarea
                  value={formData.commentaire}
                  onChange={(e) => setFormData({ ...formData, commentaire: e.target.value })}
                  placeholder="Commentaire optionnel..."
                  rows={4}
                  className="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent resize-none"
                />
              </div>
            </div>
          </div>

          {/* Colonne droite - Carte */}
          <div className="w-[700px] bg-gradient-to-br from-gray-50 to-gray-100 border-l border-gray-200 p-6 flex flex-col">
            <h3 className="text-xl font-semibold text-gray-900 mb-6">Aperçu du trajet</h3>
            
            <div className="flex-1 min-h-[600px] rounded-xl overflow-hidden shadow-lg">
              <TrajetMap
                adresseDepart={formData.adresseDepart}
                adresseArrivee={formData.adresseArrivee}
                adherentNom={formData.adherentId ? `${formData.adherentPrenom} ${formData.adherentNom}` : undefined}
              />
            </div>

            {/* Informations supplémentaires */}
            {(formData.date || formData.heure || formData.chauffeurId || formData.commentaire) && (
              <div className="mt-4 bg-white rounded-lg p-4 border border-gray-200 space-y-3">
                {formData.date && (
                  <div className="flex items-center gap-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="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <span className="text-sm text-gray-900">
                      {new Date(formData.date).toLocaleDateString('fr-FR', {
                        weekday: 'long',
                        day: 'numeric',
                        month: 'long',
                        year: 'numeric',
                      })}
                    </span>
                  </div>
                )}
                {formData.heure && (
                  <div className="flex items-center gap-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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span className="text-sm text-gray-900">{formData.heure}</span>
                  </div>
                )}
                {formData.chauffeurId && (
                  <div className="flex items-center gap-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 text-gray-900">
                      {formData.chauffeurPrenom} {formData.chauffeurNom}
                    </span>
                  </div>
                )}
                {formData.commentaire && (
                  <div className="pt-3 border-t border-gray-200">
                    <div className="text-xs font-semibold text-gray-500 uppercase mb-1">Commentaire</div>
                    <p className="text-sm text-gray-700">{formData.commentaire}</p>
                  </div>
                )}
              </div>
            )}
          </div>
        </form>

        {/* Footer */}
        <div className="border-t border-gray-200 px-6 py-4 bg-gray-50/50">
          <div className="flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors"
            >
              Annuler
            </button>
            <button
              type="submit"
              form="trajet-form"
              disabled={loading || !formData.adherentId || !formData.date || !formData.adresseDepart || !formData.adresseArrivee}
              className="px-6 py-2 bg-lgreen text-white text-sm font-medium rounded-lg hover:bg-dgreen transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {loading ? (
                <>
                  <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  {trajetToEdit ? 'Modification...' : 'Création...'}
                </>
              ) : (
                trajetToEdit ? 'Modifier le trajet' : 'Créer le trajet'
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
