import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { apiRequest } from '@/lib/queryClient';
import { useToast } from '@/hooks/use-toast';
import {
  MapPin,
  Navigation,
  Route,
  Clock,
  Fuel,
  TrendingUp,
  Zap,
  Target,
  CheckCircle,
  AlertCircle,
  RotateCcw,
  Play,
  Pause,
  Square
} from 'lucide-react';

interface DeliveryPoint {
  id: string;
  orderId: string;
  clientName: string;
  address: string;
  lat: number;
  lng: number;
  priority: 'high' | 'medium' | 'low';
  estimatedTime: number;
  status: 'pending' | 'en_route' | 'delivered' | 'failed';
  medicineType: string;
  specialInstructions?: string;
}

interface OptimizedRoute {
  id: string;
  points: DeliveryPoint[];
  totalDistance: number;
  estimatedTime: number;
  fuelCost: number;
  efficiency: number;
  startTime: string;
  endTime: string;
}

interface CourierRouteOptimizationProps {
  courierId: string;
}

export function CourierRouteOptimization({ courierId }: CourierRouteOptimizationProps) {
  const [activeRoute, setActiveRoute] = useState<OptimizedRoute | null>(null);
  const [routeStatus, setRouteStatus] = useState<'idle' | 'active' | 'paused' | 'completed'>('idle');
  const [currentPointIndex, setCurrentPointIndex] = useState(0);
  const [showMap, setShowMap] = useState(false);
  
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Fetch available delivery points
  const { data: availablePoints = [], isLoading } = useQuery<DeliveryPoint[]>({
    queryKey: ['/api/courier/delivery-points', courierId],
    initialData: [
      {
        id: '1',
        orderId: 'ord_001',
        clientName: 'Marie Assi',
        address: '123 Rue Plateau, Abidjan',
        lat: 5.3200,
        lng: -4.0300,
        priority: 'high',
        estimatedTime: 15,
        status: 'pending',
        medicineType: 'Antibiotiques',
        specialInstructions: 'Urgence médicale - Appeler avant livraison'
      },
      {
        id: '2',
        orderId: 'ord_002',
        clientName: 'Jean Kouassi',
        address: '456 Avenue Cocody, Abidjan',
        lat: 5.3600,
        lng: -4.0083,
        priority: 'medium',
        estimatedTime: 12,
        status: 'pending',
        medicineType: 'Antalgiques',
      },
      {
        id: '3',
        orderId: 'ord_003',
        clientName: 'Fatou Diabaté',
        address: '789 Boulevard Marcory, Abidjan',
        lat: 5.2800,
        lng: -3.9600,
        priority: 'low',
        estimatedTime: 18,
        status: 'pending',
        medicineType: 'Vitamines',
      },
      {
        id: '4',
        orderId: 'ord_004',
        clientName: 'Paul Bamba',
        address: '321 Rue Yopougon, Abidjan',
        lat: 5.3364,
        lng: -4.0881,
        priority: 'high',
        estimatedTime: 20,
        status: 'pending',
        medicineType: 'Insuline',
        specialInstructions: 'Réfrigération nécessaire - Livrer rapidement'
      }
    ]
  });

  // Fetch optimized routes
  const { data: suggestedRoutes = [] } = useQuery<OptimizedRoute[]>({
    queryKey: ['/api/courier/optimized-routes', courierId],
    initialData: [
      {
        id: 'route_1',
        points: availablePoints.slice(0, 3),
        totalDistance: 12.5,
        estimatedTime: 45,
        fuelCost: 2500,
        efficiency: 95,
        startTime: new Date().toISOString(),
        endTime: new Date(Date.now() + 45 * 60 * 1000).toISOString()
      },
      {
        id: 'route_2',
        points: availablePoints.slice(1, 4),
        totalDistance: 15.8,
        estimatedTime: 55,
        fuelCost: 3200,
        efficiency: 87,
        startTime: new Date().toISOString(),
        endTime: new Date(Date.now() + 55 * 60 * 1000).toISOString()
      }
    ]
  });

  // Optimize route mutation
  const optimizeRouteMutation = useMutation({
    mutationFn: async (pointIds: string[]) => {
      return await apiRequest('/api/courier/optimize-route', {
        method: 'POST',
        body: JSON.stringify({ courierId, pointIds })
      });
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['/api/courier/optimized-routes', courierId] });
      toast({
        title: "Itinéraire optimisé",
        description: "Nouvel itinéraire calculé avec succès.",
      });
    }
  });

  // Start route mutation
  const startRouteMutation = useMutation({
    mutationFn: async (routeId: string) => {
      return await apiRequest('/api/courier/start-route', {
        method: 'POST',
        body: JSON.stringify({ routeId })
      });
    },
    onSuccess: () => {
      setRouteStatus('active');
      toast({
        title: "Itinéraire démarré",
        description: "Navigation en cours vers le premier point.",
      });
    }
  });

  // Update delivery status mutation
  const updateDeliveryMutation = useMutation({
    mutationFn: async (data: { pointId: string; status: 'delivered' | 'failed'; notes?: string }) => {
      return await apiRequest('/api/courier/update-delivery', {
        method: 'PUT',
        body: JSON.stringify(data)
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/courier/delivery-points', courierId] });
      toast({
        title: "Livraison mise à jour",
        description: "Statut de livraison enregistré.",
      });
    }
  });

  const getPriorityBadge = (priority: string) => {
    const variants = {
      high: 'bg-red-100 text-red-800',
      medium: 'bg-yellow-100 text-yellow-800',
      low: 'bg-green-100 text-green-800'
    };
    
    const labels = {
      high: 'Urgent',
      medium: 'Normal',
      low: 'Différable'
    };
    
    return (
      <Badge className={variants[priority as keyof typeof variants] || 'bg-gray-100 text-gray-800'}>
        {labels[priority as keyof typeof labels] || priority}
      </Badge>
    );
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      pending: 'bg-blue-100 text-blue-800',
      en_route: 'bg-yellow-100 text-yellow-800',
      delivered: 'bg-green-100 text-green-800',
      failed: 'bg-red-100 text-red-800'
    };
    
    const labels = {
      pending: 'En attente',
      en_route: 'En route',
      delivered: 'Livré',
      failed: 'Échec'
    };
    
    return (
      <Badge className={variants[status as keyof typeof variants] || 'bg-gray-100 text-gray-800'}>
        {labels[status as keyof typeof labels] || status}
      </Badge>
    );
  };

  const startRoute = (route: OptimizedRoute) => {
    setActiveRoute(route);
    startRouteMutation.mutate(route.id);
  };

  const pauseRoute = () => {
    setRouteStatus('paused');
    toast({
      title: "Itinéraire en pause",
      description: "Vous pouvez reprendre quand vous êtes prêt.",
    });
  };

  const resumeRoute = () => {
    setRouteStatus('active');
    toast({
      title: "Itinéraire repris",
      description: "Navigation vers le prochain point.",
    });
  };

  const completeDelivery = (pointId: string, success: boolean) => {
    updateDeliveryMutation.mutate({
      pointId,
      status: success ? 'delivered' : 'failed'
    });
    
    if (activeRoute && currentPointIndex < activeRoute.points.length - 1) {
      setCurrentPointIndex(currentPointIndex + 1);
    } else {
      setRouteStatus('completed');
      toast({
        title: "Itinéraire terminé",
        description: "Toutes les livraisons ont été complétées.",
      });
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="p-6">
              <div className="animate-pulse space-y-4">
                <div className="h-4 bg-gray-200 rounded w-1/3"></div>
                <div className="h-32 bg-gray-200 rounded"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Active Route Status */}
      {activeRoute && routeStatus !== 'idle' && (
        <Card className="border-blue-200 bg-blue-50">
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center gap-2 text-blue-800">
                <Navigation className="h-5 w-5" />
                Itinéraire Actif
              </CardTitle>
              <div className="flex items-center gap-2">
                {routeStatus === 'active' && (
                  <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={pauseRoute}
                    className="text-blue-600"
                  >
                    <Pause className="h-4 w-4 mr-1" />
                    Pause
                  </Button>
                )}
                {routeStatus === 'paused' && (
                  <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={resumeRoute}
                    className="text-blue-600"
                  >
                    <Play className="h-4 w-4 mr-1" />
                    Reprendre
                  </Button>
                )}
                <Badge className={`
                  ${routeStatus === 'active' ? 'bg-green-100 text-green-800' : ''}
                  ${routeStatus === 'paused' ? 'bg-yellow-100 text-yellow-800' : ''}
                  ${routeStatus === 'completed' ? 'bg-blue-100 text-blue-800' : ''}
                `}>
                  {routeStatus === 'active' && 'En cours'}
                  {routeStatus === 'paused' && 'En pause'}
                  {routeStatus === 'completed' && 'Terminé'}
                </Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-3 gap-4 mb-6">
              <div className="flex items-center gap-2">
                <Route className="h-4 w-4 text-blue-600" />
                <div>
                  <p className="font-medium">{activeRoute.totalDistance} km</p>
                  <p className="text-sm text-muted-foreground">Distance totale</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-blue-600" />
                <div>
                  <p className="font-medium">{activeRoute.estimatedTime} min</p>
                  <p className="text-sm text-muted-foreground">Temps estimé</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Fuel className="h-4 w-4 text-blue-600" />
                <div>
                  <p className="font-medium">{activeRoute.fuelCost} F</p>
                  <p className="text-sm text-muted-foreground">Coût carburant</p>
                </div>
              </div>
            </div>

            {/* Current Delivery Point */}
            {routeStatus !== 'completed' && activeRoute.points[currentPointIndex] && (
              <div className="border rounded-lg p-4 bg-white">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-medium">Point actuel ({currentPointIndex + 1}/{activeRoute.points.length})</h4>
                  <div className="flex items-center gap-2">
                    {getPriorityBadge(activeRoute.points[currentPointIndex].priority)}
                  </div>
                </div>
                
                <div className="grid md:grid-cols-2 gap-4 mb-4">
                  <div>
                    <p className="font-medium">{activeRoute.points[currentPointIndex].clientName}</p>
                    <p className="text-sm text-muted-foreground">{activeRoute.points[currentPointIndex].address}</p>
                    <p className="text-sm text-blue-600 mt-1">
                      {activeRoute.points[currentPointIndex].medicineType}
                    </p>
                  </div>
                  <div className="flex items-center justify-end gap-2">
                    <Button 
                      variant="outline" 
                      size="sm"
                      onClick={() => completeDelivery(activeRoute.points[currentPointIndex].id, false)}
                      className="text-red-600"
                    >
                      <AlertCircle className="h-4 w-4 mr-1" />
                      Échec
                    </Button>
                    <Button 
                      size="sm"
                      onClick={() => completeDelivery(activeRoute.points[currentPointIndex].id, true)}
                    >
                      <CheckCircle className="h-4 w-4 mr-1" />
                      Livré
                    </Button>
                  </div>
                </div>

                {activeRoute.points[currentPointIndex].specialInstructions && (
                  <div className="p-3 bg-yellow-50 border border-yellow-200 rounded">
                    <div className="flex items-center gap-2">
                      <AlertCircle className="h-4 w-4 text-yellow-600" />
                      <p className="text-sm text-yellow-800">
                        <strong>Instructions spéciales:</strong> {activeRoute.points[currentPointIndex].specialInstructions}
                      </p>
                    </div>
                  </div>
                )}

                <div className="mt-4">
                  <div className="flex items-center justify-between text-sm text-muted-foreground">
                    <span>Progression</span>
                    <span>{currentPointIndex + 1} / {activeRoute.points.length}</span>
                  </div>
                  <Progress value={((currentPointIndex + 1) / activeRoute.points.length) * 100} className="mt-2" />
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      <Tabs defaultValue="optimize" className="space-y-6">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="optimize">Optimisation</TabsTrigger>
          <TabsTrigger value="points">Points de livraison</TabsTrigger>
          <TabsTrigger value="routes">Itinéraires suggérés</TabsTrigger>
        </TabsList>

        {/* Optimization Tab */}
        <TabsContent value="optimize" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Target className="h-5 w-5" />
                Optimisation d'Itinéraire
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid md:grid-cols-3 gap-6 mb-6">
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-green-600 mb-2">
                    {availablePoints.length}
                  </div>
                  <p className="text-sm text-muted-foreground">Points disponibles</p>
                </div>
                
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-blue-600 mb-2">
                    {suggestedRoutes.length}
                  </div>
                  <p className="text-sm text-muted-foreground">Routes suggérées</p>
                </div>
                
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-purple-600 mb-2">
                    {suggestedRoutes[0]?.efficiency || 0}%
                  </div>
                  <p className="text-sm text-muted-foreground">Efficacité optimale</p>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-medium">Algorithme d'optimisation intelligent</h3>
                  <p className="text-sm text-muted-foreground">
                    Calcule le meilleur itinéraire basé sur la distance, le trafic et les priorités
                  </p>
                </div>
                <Button 
                  onClick={() => optimizeRouteMutation.mutate(availablePoints.map(p => p.id))}
                  disabled={optimizeRouteMutation.isPending}
                  className="bg-gradient-to-r from-blue-600 to-purple-600"
                >
                  <Zap className="h-4 w-4 mr-1" />
                  Optimiser maintenant
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Delivery Points Tab */}
        <TabsContent value="points" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="h-5 w-5" />
                Points de Livraison Disponibles
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {availablePoints.map((point) => (
                  <div
                    key={point.id}
                    className="border rounded-lg p-4 hover:bg-gray-50 transition-colors"
                    data-testid={`delivery-point-${point.id}`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <h4 className="font-medium">{point.clientName}</h4>
                          {getPriorityBadge(point.priority)}
                          {getStatusBadge(point.status)}
                        </div>
                        
                        <div className="grid md:grid-cols-2 gap-4 text-sm">
                          <div className="flex items-center gap-2">
                            <MapPin className="h-4 w-4 text-muted-foreground" />
                            <span>{point.address}</span>
                          </div>
                          <div className="flex items-center gap-2">
                            <Clock className="h-4 w-4 text-muted-foreground" />
                            <span>{point.estimatedTime} min estimé</span>
                          </div>
                        </div>
                        
                        <div className="mt-2">
                          <p className="text-sm text-blue-600 font-medium">{point.medicineType}</p>
                          {point.specialInstructions && (
                            <p className="text-sm text-orange-600 mt-1">
                              <AlertCircle className="h-3 w-3 inline mr-1" />
                              {point.specialInstructions}
                            </p>
                          )}
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-2">
                        <Button variant="outline" size="sm">
                          <Navigation className="h-4 w-4 mr-1" />
                          Naviguer
                        </Button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Suggested Routes Tab */}
        <TabsContent value="routes" className="space-y-6">
          <div className="space-y-4">
            {suggestedRoutes.map((route, index) => (
              <Card key={route.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center gap-2">
                      <Route className="h-5 w-5" />
                      Itinéraire {index + 1}
                      <Badge className="bg-blue-100 text-blue-800">
                        {route.efficiency}% efficace
                      </Badge>
                    </CardTitle>
                    <Button 
                      onClick={() => startRoute(route)}
                      disabled={routeStatus === 'active' || startRouteMutation.isPending}
                      className="bg-gradient-to-r from-green-600 to-blue-600"
                    >
                      <Play className="h-4 w-4 mr-1" />
                      Démarrer
                    </Button>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="grid md:grid-cols-4 gap-4 mb-4">
                    <div className="flex items-center gap-2">
                      <Route className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="font-medium">{route.totalDistance} km</p>
                        <p className="text-sm text-muted-foreground">Distance</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Clock className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="font-medium">{route.estimatedTime} min</p>
                        <p className="text-sm text-muted-foreground">Temps</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Fuel className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="font-medium">{route.fuelCost} F</p>
                        <p className="text-sm text-muted-foreground">Carburant</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <TrendingUp className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="font-medium">{route.points.length} stops</p>
                        <p className="text-sm text-muted-foreground">Arrêts</p>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <h4 className="font-medium text-sm">Ordre des livraisons:</h4>
                    <div className="flex flex-wrap gap-2">
                      {route.points.map((point, pointIndex) => (
                        <div
                          key={point.id}
                          className="flex items-center gap-2 p-2 bg-gray-100 rounded text-sm"
                        >
                          <div className="w-6 h-6 rounded-full bg-primary text-white text-xs flex items-center justify-center">
                            {pointIndex + 1}
                          </div>
                          <span>{point.clientName}</span>
                          {getPriorityBadge(point.priority)}
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}