'use client';

import { useState } from 'react';
import TrajetForm from './TrajetForm';
import ValidationModal from './ValidationModal';

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 TrajetDetailModalProps {
  trajet: Trajet;
  onClose: () => void;
  onUpdate: () => void;
}

export default function TrajetDetailModal({ trajet, onClose, onUpdate }: TrajetDetailModalProps) {
  const [showEditForm, setShowEditForm] = useState(false);
  const [showValidationModal, setShowValidationModal] = useState(false);
  const [loading, setLoading] = useState(false);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    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 handleCancel = async () => {
    if (!confirm('Êtes-vous sûr de vouloir annuler ce trajet ?')) {
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`/api/trajets/${trajet.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          statut: 'Annulé',
        }),
      });

      if (response.ok) {
        onUpdate();
        onClose();
      } else {
        const error = await response.json();
        alert(error.error || 'Erreur lors de l\'annulation du trajet');
      }
    } catch (error) {
      console.error('Erreur lors de l\'annulation:', error);
      alert('Erreur lors de l\'annulation du trajet');
    } finally {
      setLoading(false);
    }
  };

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

  const getStatutColor = (statut: string) => {
    switch (statut) {
      case 'Terminé':
        return 'bg-green-100 text-green-700 border-green-200';
      case 'En cours':
        return 'bg-blue-100 text-blue-700 border-blue-200';
      case 'Annulé':
        return 'bg-red-100 text-red-700 border-red-200';
      case 'Validé':
        return 'bg-purple-100 text-purple-700 border-purple-200';
      default:
        return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  if (showEditForm) {
    return (
      <TrajetForm
        onClose={() => setShowEditForm(false)}
        onSuccess={() => {
          onUpdate();
          setShowEditForm(false);
          onClose();
        }}
        trajetToEdit={trajet}
      />
    );
  }

  if (showValidationModal) {
    return (
      <ValidationModal
        trajet={trajet}
        onClose={() => setShowValidationModal(false)}
        onSuccess={() => {
          onUpdate();
          setShowValidationModal(false);
          onClose();
        }}
      />
    );
  }

  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-2xl w-full max-h-[90vh] 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">Détails du trajet</h2>
              <p className="text-sm text-gray-500 mt-1">Informations complètes du trajet</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 */}
        <div className="flex-1 overflow-y-auto px-6 py-6">
          <div className="space-y-6">
            {/* Statut */}
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-gray-500">Statut</span>
              <span className={`px-3 py-1.5 text-sm font-semibold rounded-lg border ${getStatutColor(trajet.statut)}`}>
                {trajet.statut}
              </span>
            </div>

            {/* Adhérent */}
            <div>
              <label className="text-sm font-medium text-gray-500 mb-2 block">Adhérent</label>
              <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
                <div className="w-12 h-12 rounded-full bg-lgreen flex items-center justify-center text-white font-semibold">
                  {getInitials(trajet.adherent.nom, trajet.adherent.prenom)}
                </div>
                <div className="flex-1">
                  <div className="text-sm font-semibold text-gray-900">
                    {trajet.adherent.prenom} {trajet.adherent.nom}
                  </div>
                  <div className="text-xs text-gray-500">{trajet.adherent.email}</div>
                  <div className="text-xs text-gray-500">{trajet.adherent.telephone}</div>
                </div>
              </div>
            </div>

            {/* Chauffeur */}
            {trajet.chauffeur ? (
              <div>
                <label className="text-sm font-medium text-gray-500 mb-2 block">Chauffeur</label>
                <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
                  <div className="w-12 h-12 rounded-full bg-lblue flex items-center justify-center text-white font-semibold">
                    {getInitials(trajet.chauffeur.nom, trajet.chauffeur.prenom)}
                  </div>
                  <div className="flex-1">
                    <div className="text-sm font-semibold text-gray-900">
                      {trajet.chauffeur.prenom} {trajet.chauffeur.nom}
                    </div>
                    <div className="text-xs text-gray-500">{trajet.chauffeur.telephone}</div>
                  </div>
                </div>
              </div>
            ) : (
              <div>
                <label className="text-sm font-medium text-gray-500 mb-2 block">Chauffeur</label>
                <div className="p-3 bg-orange-50 rounded-lg border border-orange-200">
                  <div className="flex items-center gap-2 text-orange-700">
                    <svg className="w-5 h-5" 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 font-medium">Aucun chauffeur assigné</span>
                  </div>
                </div>
              </div>
            )}

            {/* Date et heure */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-gray-500 mb-2 block">Date</label>
                <div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg border border-gray-200">
                  <svg className="w-5 h-5 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 font-medium text-gray-900">{formatDate(trajet.date)}</span>
                </div>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-500 mb-2 block">Heure</label>
                <div className="flex items-center gap-2 p-3 bg-gray-50 rounded-lg border border-gray-200">
                  <svg className="w-5 h-5 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 font-medium text-gray-900">{formatTime(trajet.date)}</span>
                </div>
              </div>
            </div>

            {/* Adresses */}
            <div>
              <label className="text-sm font-medium text-gray-500 mb-2 block">Adresse de départ</label>
              <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
                <div className="flex items-start gap-2">
                  <div className="w-6 h-6 rounded-full bg-lgreen flex items-center justify-center text-white text-xs font-bold mt-0.5 flex-shrink-0">
                    A
                  </div>
                  <span className="text-sm text-gray-900">{trajet.adresseDepart}</span>
                </div>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium text-gray-500 mb-2 block">Adresse d'arrivée</label>
              <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
                <div className="flex items-start gap-2">
                  <div className="w-6 h-6 rounded-full bg-lblue flex items-center justify-center text-white text-xs font-bold mt-0.5 flex-shrink-0">
                    B
                  </div>
                  <span className="text-sm text-gray-900">{trajet.adresseArrivee}</span>
                </div>
              </div>
            </div>

            {/* Commentaire */}
            {trajet.commentaire && (
              <div>
                <label className="text-sm font-medium text-gray-500 mb-2 block">Commentaire</label>
                <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
                  <p className="text-sm text-gray-700 whitespace-pre-wrap">{trajet.commentaire}</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="border-t border-gray-200 px-6 py-4 bg-gray-50/50">
          <div className="flex justify-between gap-3">
            <button
              type="button"
              onClick={handleCancel}
              disabled={loading || trajet.statut === 'Validé' || trajet.statut === 'Terminé' || trajet.statut === 'Annulé'}
              className="px-4 py-2 text-sm font-medium text-red-600 hover:text-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
              {trajet.statut === 'Annulé' ? 'Trajet annulé' : 'Annuler le trajet'}
            </button>
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setShowEditForm(true)}
                disabled={trajet.statut === 'Validé' || trajet.statut === 'Terminé'}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
                Modifier
              </button>
              {trajet.chauffeur && trajet.statut === 'Planifié' && (
                <button
                  type="button"
                  onClick={() => setShowValidationModal(true)}
                  className="px-6 py-2 bg-lgreen text-white text-sm font-medium rounded-lg hover:bg-dgreen transition-colors flex items-center gap-2"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
                  Valider le trajet
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
