import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Map, MapMarker } from './Map';
import { GeolocationService, Location } from '@/services/geolocation';
import { MapPin, Clock, Route, Truck } from 'lucide-react';

export interface OrderTrackingData {
  id: string;
  status: string;
  clientLocation: Location;
  pharmacyLocation?: Location;
  courierLocation?: Location;
  deliveryAddress: Location;
  estimatedDeliveryTime?: string;
  courierName?: string;
  pharmacyName?: string;
}

interface OrderTrackingMapProps {
  order: OrderTrackingData;
  showEstimates?: boolean;
  height?: string;
  refreshInterval?: number;
}

const statusConfig = {
  'CREATED': { label: 'Commande créée', color: 'bg-blue-100 text-blue-800' },
  'PHARMACY_CONFIRMED': { label: 'Confirmée par la pharmacie', color: 'bg-green-100 text-green-800' },
  'COURIER_ASSIGNED': { label: 'Livreur assigné', color: 'bg-yellow-100 text-yellow-800' },
  'PICKED_UP': { label: 'Récupéré', color: 'bg-orange-100 text-orange-800' },
  'IN_TRANSIT': { label: 'En livraison', color: 'bg-purple-100 text-purple-800' },
  'DELIVERED': { label: 'Livré', color: 'bg-green-100 text-green-800' },
  'CANCELLED': { label: 'Annulé', color: 'bg-red-100 text-red-800' }
};

export function OrderTrackingMap({ 
  order, 
  showEstimates = true, 
  height = '400px',
  refreshInterval = 30000 // 30 seconds
}: OrderTrackingMapProps) {
  const [distances, setDistances] = useState<{
    clientToPharmacy?: number;
    pharmacyToDelivery?: number;
    courierToPharmacy?: number;
    courierToDelivery?: number;
  }>({});

  const geoService = GeolocationService.getInstance();

  // Calculate distances when locations change
  useEffect(() => {
    const newDistances: typeof distances = {};

    if (order.pharmacyLocation) {
      const clientToPharmacy = geoService.calculateDistance(order.clientLocation, order.pharmacyLocation);
      newDistances.clientToPharmacy = clientToPharmacy.distance;

      if (order.deliveryAddress) {
        const pharmacyToDelivery = geoService.calculateDistance(order.pharmacyLocation, order.deliveryAddress);
        newDistances.pharmacyToDelivery = pharmacyToDelivery.distance;
      }
    }

    if (order.courierLocation) {
      if (order.pharmacyLocation && order.status === 'COURIER_ASSIGNED') {
        const courierToPharmacy = geoService.calculateDistance(order.courierLocation, order.pharmacyLocation);
        newDistances.courierToPharmacy = courierToPharmacy.distance;
      }

      if (order.status === 'PICKED_UP' || order.status === 'IN_TRANSIT') {
        const courierToDelivery = geoService.calculateDistance(order.courierLocation, order.deliveryAddress);
        newDistances.courierToDelivery = courierToDelivery.distance;
      }
    }

    setDistances(newDistances);
  }, [order, geoService]);

  // Build markers based on order status and available locations
  const markers: MapMarker[] = [];

  // Client location (pickup point)
  markers.push({
    id: 'client',
    lat: order.clientLocation.lat,
    lng: order.clientLocation.lng,
    title: 'Point de récupération',
    type: 'client',
    info: order.clientLocation.address || 'Adresse du client'
  });

  // Pharmacy location
  if (order.pharmacyLocation) {
    markers.push({
      id: 'pharmacy',
      lat: order.pharmacyLocation.lat,
      lng: order.pharmacyLocation.lng,
      title: order.pharmacyName || 'Pharmacie',
      type: 'pharmacy',
      info: order.pharmacyLocation.address || 'Pharmacie assignée',
      status: distances.clientToPharmacy ? `${geoService.formatDistance(distances.clientToPharmacy)}` : undefined
    });
  }

  // Courier location (if assigned and moving)
  if (order.courierLocation && ['COURIER_ASSIGNED', 'PICKED_UP', 'IN_TRANSIT'].includes(order.status)) {
    let courierInfo = order.courierName || 'Livreur';
    if (distances.courierToPharmacy && order.status === 'COURIER_ASSIGNED') {
      courierInfo += ` - ${geoService.formatDistance(distances.courierToPharmacy)} de la pharmacie`;
    } else if (distances.courierToDelivery && (order.status === 'PICKED_UP' || order.status === 'IN_TRANSIT')) {
      courierInfo += ` - ${geoService.formatDistance(distances.courierToDelivery)} de la destination`;
    }

    markers.push({
      id: 'courier',
      lat: order.courierLocation.lat,
      lng: order.courierLocation.lng,
      title: order.courierName || 'Livreur',
      type: 'courier',
      info: courierInfo,
      status: order.status === 'PICKED_UP' ? 'En cours de livraison' : 'En déplacement'
    });
  }

  // Delivery destination (if different from client location)
  if (order.deliveryAddress && 
      (order.deliveryAddress.lat !== order.clientLocation.lat || 
       order.deliveryAddress.lng !== order.clientLocation.lng)) {
    markers.push({
      id: 'destination',
      lat: order.deliveryAddress.lat,
      lng: order.deliveryAddress.lng,
      title: 'Adresse de livraison',
      type: 'destination',
      info: order.deliveryAddress.address || 'Destination finale'
    });
  }

  // Calculate map center (focus on the most relevant location)
  const getMapCenter = (): [number, number] => {
    if (order.courierLocation && ['COURIER_ASSIGNED', 'PICKED_UP', 'IN_TRANSIT'].includes(order.status)) {
      return [order.courierLocation.lat, order.courierLocation.lng];
    }
    if (order.pharmacyLocation && ['PHARMACY_CONFIRMED', 'COURIER_ASSIGNED'].includes(order.status)) {
      return [order.pharmacyLocation.lat, order.pharmacyLocation.lng];
    }
    return [order.clientLocation.lat, order.clientLocation.lng];
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <MapPin className="h-5 w-5" />
            Suivi de livraison
          </CardTitle>
          <Badge className={statusConfig[order.status as keyof typeof statusConfig]?.color || 'bg-gray-100 text-gray-800'}>
            {statusConfig[order.status as keyof typeof statusConfig]?.label || order.status}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Map */}
        <Map
          center={getMapCenter()}
          zoom={14}
          markers={markers}
          height={height}
          interactive={true}
          className="border-2 border-primary/20"
        />

        {/* Distance and Time Estimates */}
        {showEstimates && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Pharmacy Distance */}
            {distances.clientToPharmacy && (
              <div className="flex items-center gap-3 p-3 bg-green-50 rounded-lg">
                <div className="bg-green-100 p-2 rounded-full">
                  <Route className="h-4 w-4 text-green-600" />
                </div>
                <div>
                  <div className="font-medium text-green-800">Distance à la pharmacie</div>
                  <div className="text-sm text-green-600">
                    {geoService.formatDistance(distances.clientToPharmacy)}
                  </div>
                </div>
              </div>
            )}

            {/* Delivery Distance */}
            {distances.pharmacyToDelivery && (
              <div className="flex items-center gap-3 p-3 bg-blue-50 rounded-lg">
                <div className="bg-blue-100 p-2 rounded-full">
                  <Truck className="h-4 w-4 text-blue-600" />
                </div>
                <div>
                  <div className="font-medium text-blue-800">Distance de livraison</div>
                  <div className="text-sm text-blue-600">
                    {geoService.formatDistance(distances.pharmacyToDelivery)}
                  </div>
                </div>
              </div>
            )}

            {/* Courier to Pharmacy */}
            {distances.courierToPharmacy && order.status === 'COURIER_ASSIGNED' && (
              <div className="flex items-center gap-3 p-3 bg-yellow-50 rounded-lg">
                <div className="bg-yellow-100 p-2 rounded-full">
                  <Route className="h-4 w-4 text-yellow-600" />
                </div>
                <div>
                  <div className="font-medium text-yellow-800">Livreur vers pharmacie</div>
                  <div className="text-sm text-yellow-600">
                    {geoService.formatDistance(distances.courierToPharmacy)}
                  </div>
                </div>
              </div>
            )}

            {/* Courier to Delivery */}
            {distances.courierToDelivery && (order.status === 'PICKED_UP' || order.status === 'IN_TRANSIT') && (
              <div className="flex items-center gap-3 p-3 bg-purple-50 rounded-lg">
                <div className="bg-purple-100 p-2 rounded-full">
                  <Truck className="h-4 w-4 text-purple-600" />
                </div>
                <div>
                  <div className="font-medium text-purple-800">Livreur vers destination</div>
                  <div className="text-sm text-purple-600">
                    {geoService.formatDistance(distances.courierToDelivery)}
                  </div>
                </div>
              </div>
            )}

            {/* Estimated Delivery Time */}
            {order.estimatedDeliveryTime && (
              <div className="flex items-center gap-3 p-3 bg-orange-50 rounded-lg md:col-span-2">
                <div className="bg-orange-100 p-2 rounded-full">
                  <Clock className="h-4 w-4 text-orange-600" />
                </div>
                <div>
                  <div className="font-medium text-orange-800">Heure de livraison estimée</div>
                  <div className="text-sm text-orange-600">
                    {order.estimatedDeliveryTime}
                  </div>
                </div>
              </div>
            )}
          </div>
        )}

        {/* Order Timeline */}
        <div className="border-t pt-4">
          <h4 className="font-medium mb-3">Statut de la commande</h4>
          <div className="space-y-2">
            <div className="flex items-center gap-3">
              <div className={`w-3 h-3 rounded-full ${order.status !== 'CREATED' ? 'bg-green-500' : 'bg-green-300'}`}></div>
              <span className={order.status === 'CREATED' ? 'font-medium' : 'text-gray-600'}>
                Commande créée
              </span>
            </div>
            {order.pharmacyName && (
              <div className="flex items-center gap-3">
                <div className={`w-3 h-3 rounded-full ${['PHARMACY_CONFIRMED', 'COURIER_ASSIGNED', 'PICKED_UP', 'IN_TRANSIT', 'DELIVERED'].includes(order.status) ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                <span className={order.status === 'PHARMACY_CONFIRMED' ? 'font-medium' : 'text-gray-600'}>
                  Confirmée par {order.pharmacyName}
                </span>
              </div>
            )}
            {order.courierName && (
              <div className="flex items-center gap-3">
                <div className={`w-3 h-3 rounded-full ${['COURIER_ASSIGNED', 'PICKED_UP', 'IN_TRANSIT', 'DELIVERED'].includes(order.status) ? 'bg-green-500' : 'bg-gray-300'}`}></div>
                <span className={order.status === 'COURIER_ASSIGNED' ? 'font-medium' : 'text-gray-600'}>
                  Livreur {order.courierName} assigné
                </span>
              </div>
            )}
            <div className="flex items-center gap-3">
              <div className={`w-3 h-3 rounded-full ${order.status === 'DELIVERED' ? 'bg-green-500' : 'bg-gray-300'}`}></div>
              <span className={order.status === 'DELIVERED' ? 'font-medium text-green-600' : 'text-gray-600'}>
                Livraison terminée
              </span>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}