import { useState, useEffect } from 'react';
import { Map, MapMarker } from './Map';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { useRealTimeTracking } from '@/hooks/useGeolocation';
import { geolocationService } from '@/services/geolocationService';
import { 
  Navigation, 
  MapPin, 
  Clock, 
  Truck, 
  Package,
  Route,
  Target
} from 'lucide-react';

interface DeliveryLocation {
  lat: number;
  lng: number;
  address: string;
  type: 'pickup' | 'destination';
  name?: string;
  phone?: string;
  notes?: string;
}

interface CourierInfo {
  id: string;
  name: string;
  phone: string;
  vehicle: 'bike' | 'motorcycle' | 'car';
  rating: number;
  currentLocation?: { lat: number; lng: number };
}

interface DeliveryTrackingMapProps {
  orderId: string;
  pickup: DeliveryLocation;
  destination: DeliveryLocation;
  courier?: CourierInfo;
  status: string;
  estimatedArrival?: Date;
  onLocationUpdate?: (lat: number, lng: number) => void;
  height?: string;
  showRoute?: boolean;
  realTime?: boolean;
}

export function DeliveryTrackingMap({
  orderId,
  pickup,
  destination,
  courier,
  status,
  estimatedArrival,
  onLocationUpdate,
  height = '400px',
  showRoute = true,
  realTime = true
}: DeliveryTrackingMapProps) {
  const [courierLocation, setCourierLocation] = useState(courier?.currentLocation);
  const [routeProgress, setRouteProgress] = useState(0);
  const [estimatedTimeRemaining, setEstimatedTimeRemaining] = useState<number | null>(null);

  const {
    trackedLocations,
    isTracking,
    startTrackingTarget,
    currentLocation
  } = useRealTimeTracking(courier?.id);

  // Start tracking when component mounts
  useEffect(() => {
    if (courier?.id && realTime && status === 'IN_TRANSIT') {
      startTrackingTarget(courier.id);
    }
  }, [courier?.id, realTime, status, startTrackingTarget]);

  // Update courier location from tracking
  useEffect(() => {
    if (courier?.id && trackedLocations.has(courier.id)) {
      const newLocation = trackedLocations.get(courier.id);
      if (newLocation) {
        setCourierLocation(newLocation);
        onLocationUpdate?.(newLocation.lat, newLocation.lng);
      }
    }
  }, [trackedLocations, courier?.id, onLocationUpdate]);

  // Calculate route progress and estimated time
  useEffect(() => {
    if (courierLocation && pickup && destination) {
      const totalDistance = geolocationService.calculateDistance(pickup, destination).distance;
      const distanceFromPickup = geolocationService.calculateDistance(pickup, courierLocation).distance;
      
      // Calculate progress (0% at pickup, 100% at destination)
      let progress = Math.min((distanceFromPickup / totalDistance) * 100, 100);
      if (status === 'COURIER_ASSIGNED' || status === 'PICKED_UP') {
        progress = Math.max(progress, 10); // Minimum 10% when picked up
      }
      
      setRouteProgress(progress);

      // Estimate time remaining
      if (status === 'IN_TRANSIT') {
        const remainingDistance = geolocationService.calculateDistance(courierLocation, destination).distance;
        const estimatedDuration = geolocationService.calculateDistance(courierLocation, destination).duration;
        setEstimatedTimeRemaining(estimatedDuration);
      }
    }
  }, [courierLocation, pickup, destination, status]);

  // Create map markers
  const markers: MapMarker[] = [];

  // Add pickup location
  markers.push({
    id: 'pickup',
    lat: pickup.lat,
    lng: pickup.lng,
    title: pickup.name || 'Point de récupération',
    type: 'pickup',
    address: pickup.address,
    info: pickup.notes || 'Pharmacie',
    isActive: status === 'COURIER_ASSIGNED'
  });

  // Add destination
  markers.push({
    id: 'destination',
    lat: destination.lat,
    lng: destination.lng,
    title: destination.name || 'Destination',
    type: 'destination',
    address: destination.address,
    info: destination.phone || 'Adresse de livraison',
    isActive: status === 'IN_TRANSIT'
  });

  // Add courier location if available
  if (courierLocation) {
    markers.push({
      id: 'courier',
      lat: courierLocation.lat,
      lng: courierLocation.lng,
      title: courier?.name || 'Livreur',
      type: 'courier',
      info: `${courier?.vehicle || 'Véhicule'} • En cours`,
      isActive: true
    });
  }

  // Calculate map center
  const allPoints = [pickup, destination, ...(courierLocation ? [courierLocation] : [])];
  const centerLat = allPoints.reduce((sum, point) => sum + point.lat, 0) / allPoints.length;
  const centerLng = allPoints.reduce((sum, point) => sum + point.lng, 0) / allPoints.length;

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

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      'COURIER_ASSIGNED': 'Livreur assigné',
      'PICKED_UP': 'Commande récupérée',
      'IN_TRANSIT': 'En cours de livraison',
      'DELIVERED': 'Livré'
    };
    return labels[status] || status;
  };

  const getVehicleIcon = (vehicle?: string) => {
    switch (vehicle) {
      case 'bike': return '🚲';
      case 'motorcycle': return '🏍️';
      case 'car': return '🚗';
      default: return '🚴';
    }
  };

  return (
    <div className="space-y-4">
      {/* Status Header */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className={`w-3 h-3 rounded-full ${getStatusColor(status)} animate-pulse`} />
              <span className="font-medium">{getStatusLabel(status)}</span>
              <Badge variant="outline">#{orderId.substring(0, 8)}</Badge>
            </div>
            
            {isTracking && (
              <Badge variant="secondary" className="flex items-center gap-1">
                <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
                Suivi actif
              </Badge>
            )}
          </div>

          {/* Progress Bar */}
          <div className="space-y-2">
            <div className="flex items-center justify-between text-sm">
              <span>Progression</span>
              <span>{Math.round(routeProgress)}%</span>
            </div>
            <Progress value={routeProgress} className="h-2" />
          </div>

          {/* Time Information */}
          <div className="grid grid-cols-2 gap-4 mt-4">
            {estimatedArrival && (
              <div className="flex items-center gap-2 text-sm">
                <Clock className="h-4 w-4 text-blue-500" />
                <div>
                  <div className="font-medium">Arrivée prévue</div>
                  <div className="text-muted-foreground">
                    {estimatedArrival.toLocaleTimeString('fr-FR', { 
                      hour: '2-digit', 
                      minute: '2-digit' 
                    })}
                  </div>
                </div>
              </div>
            )}
            
            {estimatedTimeRemaining && (
              <div className="flex items-center gap-2 text-sm">
                <Target className="h-4 w-4 text-green-500" />
                <div>
                  <div className="font-medium">Temps restant</div>
                  <div className="text-muted-foreground">
                    {geolocationService.formatDuration(estimatedTimeRemaining)}
                  </div>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Courier Info */}
      {courier && (
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center">
                <span className="text-lg">{getVehicleIcon(courier.vehicle)}</span>
              </div>
              <div className="flex-1">
                <div className="font-medium">{courier.name}</div>
                <div className="text-sm text-muted-foreground">
                  {courier.vehicle} • {courier.rating}⭐
                </div>
              </div>
              <div className="flex gap-2">
                <Badge variant="outline" className="text-xs">
                  <Navigation className="h-3 w-3 mr-1" />
                  {courierLocation ? 'En ligne' : 'Hors ligne'}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Map */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2">
            <MapPin className="h-5 w-5" />
            Suivi en temps réel
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <Map
            center={[centerLat, centerLng]}
            zoom={13}
            markers={markers}
            height={height}
            showUserLocation={false}
            interactive={true}
            realTimeTracking={realTime}
          />
        </CardContent>
      </Card>

      {/* Route Details */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2">
            <Route className="h-5 w-5" />
            Détails du trajet
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex items-start gap-3">
            <div className="w-6 h-6 bg-purple-100 rounded-full flex items-center justify-center mt-1">
              <Package className="h-3 w-3 text-purple-600" />
            </div>
            <div className="flex-1">
              <div className="font-medium">Point de récupération</div>
              <div className="text-sm text-muted-foreground">{pickup.address}</div>
              {pickup.phone && (
                <div className="text-xs text-muted-foreground">{pickup.phone}</div>
              )}
            </div>
            {status !== 'COURIER_ASSIGNED' && (
              <Badge variant="secondary" className="text-xs">✓</Badge>
            )}
          </div>

          <div className="border-l-2 border-dashed border-gray-200 ml-3 h-8"></div>

          <div className="flex items-start gap-3">
            <div className="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center mt-1">
              <MapPin className="h-3 w-3 text-red-600" />
            </div>
            <div className="flex-1">
              <div className="font-medium">Destination</div>
              <div className="text-sm text-muted-foreground">{destination.address}</div>
              {destination.phone && (
                <div className="text-xs text-muted-foreground">{destination.phone}</div>
              )}
            </div>
            {status === 'DELIVERED' && (
              <Badge variant="secondary" className="text-xs">✓</Badge>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}