import { useState, useEffect } from 'react';
// import { useWebSocket } from '@/hooks/useWebSocket'; // TODO: Fix WebSocket hook
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
// import { Map, MapMarker } from '@/components/maps/Map'; // TODO: Fix map component import
import { 
  Clock, 
  MapPin, 
  Truck, 
  Package, 
  CheckCircle, 
  AlertCircle,
  Phone,
  Navigation,
  Pill
} from 'lucide-react';

interface OrderTrackerProps {
  orderId: string;
  initialOrder?: any;
  onUpdateStatus?: (status: string) => void;
  userRole?: 'client' | 'pharmacy' | 'courier' | 'admin';
}

interface OrderStatus {
  step: number;
  label: string;
  status: 'completed' | 'current' | 'pending';
  timestamp?: Date;
  description?: string;
}

export function OrderTracker({ orderId, initialOrder, onUpdateStatus, userRole = 'client' }: OrderTrackerProps) {
  // TODO: Fix WebSocket hooks when available
  const isConnected = false;
  const subscribeToOrder = (id: string) => {};
  const sendLocationUpdate = (location: { lat: number; lng: number }) => {};
  const [order, setOrder] = useState(initialOrder);
  const [courierLocation, setCourierLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [isTrackingLocation, setIsTrackingLocation] = useState(false);
  const [estimatedArrival, setEstimatedArrival] = useState<Date | null>(null);

  // Subscribe to order updates when connected
  useEffect(() => {
    if (isConnected) {
      subscribeToOrder(orderId);
    }
  }, [isConnected, orderId, subscribeToOrder]);

  // Listen for WebSocket updates
  useEffect(() => {
    const handleWebSocketMessage = (event: any) => {
      const message = JSON.parse(event.data);
      
      switch (message.type) {
        case 'order_status_change':
          if (message.orderId === orderId) {
            setOrder((prev: any) => ({
              ...prev,
              status: message.status,
              ...message.details
            }));
            onUpdateStatus?.(message.status);
          }
          break;
          
        case 'courier_location':
          if (message.data?.orderId === orderId) {
            setCourierLocation(message.data.location);
            updateEstimatedArrival(message.data.location);
          }
          break;
      }
    };

    if (isConnected) {
      // In a real implementation, this would be handled by the WebSocket hook
      // For now, we'll simulate the subscription
    }

    return () => {
      // Cleanup subscription
    };
  }, [isConnected, orderId, onUpdateStatus]);

  // Track courier location (for courier role)
  useEffect(() => {
    if (userRole === 'courier' && isTrackingLocation) {
      const watchId = navigator.geolocation.watchPosition(
        (position) => {
          const location = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          sendLocationUpdate(location);
        },
        (error) => console.error('Geolocation error:', error),
        { enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 }
      );

      return () => {
        navigator.geolocation.clearWatch(watchId);
      };
    }
  }, [userRole, isTrackingLocation, sendLocationUpdate]);

  const updateEstimatedArrival = (location: { lat: number; lng: number }) => {
    if (order?.clientLat && order?.clientLng) {
      // Calculate estimated time based on distance
      const distance = calculateDistance(
        location,
        { lat: order.clientLat, lng: order.clientLng }
      );
      const estimatedMinutes = Math.ceil(distance * 2); // Assume 30km/h average speed
      setEstimatedArrival(new Date(Date.now() + estimatedMinutes * 60 * 1000));
    }
  };

  const calculateDistance = (point1: { lat: number; lng: number }, point2: { lat: number; lng: number }) => {
    const R = 6371; // Earth's radius in km
    const dLat = (point2.lat - point1.lat) * Math.PI / 180;
    const dLng = (point2.lng - point1.lng) * Math.PI / 180;
    const a = Math.sin(dLat/2) * Math.sin(dLng/2) +
              Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) *
              Math.sin(dLng/2) * Math.sin(dLng/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
  };

  const getOrderProgress = (): { progress: number; statuses: OrderStatus[] } => {
    const baseStatuses: OrderStatus[] = [
      { step: 1, label: 'Commande créée', status: 'completed', description: 'Demande SOS envoyée' },
      { step: 2, label: 'Pharmacie confirmée', status: 'pending', description: 'Recherche de pharmacie' },
      { step: 3, label: 'Livreur assigné', status: 'pending', description: 'Attribution du livreur' },
      { step: 4, label: 'Récupération', status: 'pending', description: 'Récupération en pharmacie' },
      { step: 5, label: 'En cours', status: 'pending', description: 'Livraison en cours' },
      { step: 6, label: 'Livré', status: 'pending', description: 'Livraison terminée' }
    ];

    const statusMap: Record<string, number> = {
      'CREATED': 1,
      'PHARMACY_CONFIRMED': 2,
      'COURIER_ASSIGNED': 3,
      'PICKED_UP': 4,
      'IN_TRANSIT': 5,
      'DELIVERED': 6
    };

    const currentStep = statusMap[order?.status] || 1;
    const progress = ((currentStep - 1) / 5) * 100;

    const statuses = baseStatuses.map((status, index) => ({
      ...status,
      status: index + 1 < currentStep ? 'completed' : 
              index + 1 === currentStep ? 'current' : 'pending'
    }));

    return { progress, statuses };
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'CREATED': 'bg-blue-500',
      'PHARMACY_CONFIRMED': 'bg-green-500',
      'COURIER_ASSIGNED': 'bg-purple-500',
      'PICKED_UP': 'bg-yellow-500',
      'IN_TRANSIT': 'bg-orange-500',
      'DELIVERED': 'bg-green-600',
      'CANCELLED': 'bg-red-500',
      'NO_PHARMACY_AVAILABLE': 'bg-gray-500'
    };
    return colors[status] || 'bg-gray-400';
  };

  const handleStatusUpdate = async (newStatus: string) => {
    try {
      // In a real implementation, call API to update status
      console.log(`Updating order ${orderId} to status: ${newStatus}`);
      onUpdateStatus?.(newStatus);
    } catch (error) {
      console.error('Error updating order status:', error);
    }
  };

  const toggleLocationTracking = () => {
    setIsTrackingLocation(!isTrackingLocation);
  };

  if (!order) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="text-center">
            <AlertCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500">Commande non trouvée</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  const { progress, statuses } = getOrderProgress();

  // Create map markers (TODO: Implement when Map component is available)
  // const markers: MapMarker[] = [];
  
  // if (order.clientLat && order.clientLng) {
  //   markers.push({
  //     id: 'client',
  //     lat: order.clientLat,
  //     lng: order.clientLng,
  //     title: 'Adresse de livraison',
  //     type: 'destination',
  //     info: order.clientPhone
  //   });
  // }

  // if (courierLocation) {
  //   markers.push({
  //     id: 'courier',
  //     lat: courierLocation.lat,
  //     lng: courierLocation.lng,
  //     title: 'Position du livreur',
  //     type: 'courier',
  //     info: 'En cours de livraison'
  //   });
  // }

  return (
    <div className="space-y-6" data-testid="order-tracker">
      {/* Order Header */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              Commande #{orderId.substring(0, 8)}
            </CardTitle>
            <Badge 
              className={`${getStatusColor(order.status)} text-white`}
              data-testid="order-status"
            >
              {order.status}
            </Badge>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="flex items-center gap-2">
              <Pill className="h-4 w-4 text-blue-500" />
              <span className="font-medium">{order.medicineName}</span>
              <span className="text-muted-foreground">x{order.quantity}</span>
            </div>
            <div className="flex items-center gap-2">
              <Phone className="h-4 w-4 text-green-500" />
              <span>{order.clientPhone}</span>
            </div>
            {estimatedArrival && (
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-orange-500" />
                <span>Livraison: {estimatedArrival.toLocaleTimeString('fr-FR', { 
                  hour: '2-digit', 
                  minute: '2-digit' 
                })}</span>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Progress Tracker */}
      <Card>
        <CardHeader>
          <CardTitle>Suivi de livraison</CardTitle>
          <Progress value={progress} className="mt-2" data-testid="progress-bar" />
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {statuses.map((status) => (
              <div 
                key={status.step}
                className={`flex items-center gap-3 p-3 rounded-lg transition-colors ${
                  status.status === 'current' ? 'bg-blue-50 border-l-4 border-blue-500' :
                  status.status === 'completed' ? 'bg-green-50' : 'bg-gray-50'
                }`}
                data-testid={`status-step-${status.step}`}
              >
                {status.status === 'completed' ? (
                  <CheckCircle className="h-5 w-5 text-green-500" />
                ) : status.status === 'current' ? (
                  <Clock className="h-5 w-5 text-blue-500 animate-pulse" />
                ) : (
                  <div className="h-5 w-5 rounded-full border-2 border-gray-300" />
                )}
                <div className="flex-1">
                  <p className={`font-medium ${
                    status.status === 'current' ? 'text-blue-700' : 
                    status.status === 'completed' ? 'text-green-700' : 'text-gray-500'
                  }`}>
                    {status.label}
                  </p>
                  <p className="text-sm text-muted-foreground">{status.description}</p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Map Tracking */}
      {(order.clientLat && order.clientLng) && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5" />
              Suivi en temps réel
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[300px] bg-gray-100 rounded-lg flex items-center justify-center">
              <div className="text-center">
                <MapPin className="h-12 w-12 text-gray-400 mx-auto mb-2" />
                <p className="text-gray-500">Carte interactive avec Leaflet</p>
                {courierLocation && (
                  <p className="text-sm text-blue-600 mt-2">
                    Position livreur: {courierLocation.lat.toFixed(4)}, {courierLocation.lng.toFixed(4)}
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Courier Controls */}
      {userRole === 'courier' && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Truck className="h-5 w-5" />
              Contrôles livreur
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-4">
              <Button
                variant={isTrackingLocation ? "destructive" : "default"}
                onClick={toggleLocationTracking}
                className="flex items-center gap-2"
                data-testid="toggle-tracking"
              >
                <Navigation className="h-4 w-4" />
                {isTrackingLocation ? 'Arrêter le suivi' : 'Activer le suivi GPS'}
              </Button>
              {isTrackingLocation && (
                <Badge variant="secondary" className="animate-pulse">
                  Localisation en cours...
                </Badge>
              )}
            </div>

            <div className="grid grid-cols-2 gap-2">
              {order.status === 'COURIER_ASSIGNED' && (
                <Button
                  onClick={() => handleStatusUpdate('PICKED_UP')}
                  className="bg-yellow-500 hover:bg-yellow-600"
                  data-testid="mark-picked-up"
                >
                  Marquer comme récupéré
                </Button>
              )}
              {order.status === 'PICKED_UP' && (
                <Button
                  onClick={() => handleStatusUpdate('IN_TRANSIT')}
                  className="bg-orange-500 hover:bg-orange-600"
                  data-testid="mark-in-transit"
                >
                  En cours de livraison
                </Button>
              )}
              {order.status === 'IN_TRANSIT' && (
                <Button
                  onClick={() => handleStatusUpdate('DELIVERED')}
                  className="bg-green-500 hover:bg-green-600"
                  data-testid="mark-delivered"
                >
                  Marquer comme livré
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Connection Status */}
      <div className="flex items-center justify-center">
        <Badge 
          variant={isConnected ? "default" : "destructive"}
          className="flex items-center gap-2"
          data-testid="connection-status"
        >
          <div className={`h-2 w-2 rounded-full ${isConnected ? 'bg-green-400 animate-pulse' : 'bg-red-400'}`} />
          {isConnected ? 'Connecté' : 'Déconnecté'}
        </Badge>
      </div>
    </div>
  );
}