import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { CourierRouteOptimization } from '@/components/courier-route-optimization';
import { CourierEarningsDashboard } from '@/components/courier-earnings-dashboard';
import { DeliveryTrackingMap } from '@/components/maps/DeliveryTrackingMap';
import { ORDER_STATUSES } from '@/lib/constants';
import { OrderWithDetails } from '@shared/schema';
import { useAuth } from '@/contexts/AuthContext';
import {
  Truck,
  MapPin,
  Clock,
  Route,
  Pill,
  User,
  Phone,
  CheckCircle,
  Package,
  Star,
  DollarSign,
  History,
  Wallet,
  AlertCircle,
  Check,
  Navigation,
  Activity,
  TrendingUp,
  Target,
  Fuel,
  Award
} from 'lucide-react';

export function EnhancedCourierDashboard() {
  const { user, isAuthenticated } = useAuth();
  const [activeTab, setActiveTab] = useState('overview');
  
  // Redirect if not authenticated or not a courier
  if (!isAuthenticated || !user) {
    return (
      <div className="container mx-auto p-4">
        <Alert>
          <AlertDescription>
            Vous devez être connecté en tant que livreur pour accéder à cette page.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  if (user.role !== 'courier') {
    return (
      <div className="container mx-auto p-4">
        <Alert>
          <AlertDescription>
            Cette page est réservée aux livreurs.
          </AlertDescription>
        </Alert>
      </div>
    );
  }
  
  const courierData = (user as any).courier || { 
    isAvailable: true, 
    currentLocation: { lat: 5.3364, lng: -4.0267 },
    vehicleType: 'Moto',
    verified: true
  };
  const [isAvailable, setIsAvailable] = useState(courierData.isAvailable || true);

  // Fetch available orders for courier
  const { data: availableOrders = [], isLoading: loadingAvailable } = useQuery<OrderWithDetails[]>({
    queryKey: ['/api/courier/available-orders', { 
      courierId: user.id,
      lat: courierData.currentLocation?.lat || 5.3364,
      lng: courierData.currentLocation?.lng || -4.0267
    }],
    enabled: isAvailable && isAuthenticated && !!user?.id
  });

  // Fetch current active delivery
  const { data: activeDeliveries = [] } = useQuery<OrderWithDetails[]>({
    queryKey: ['/api/orders', { 
      userId: user.id, 
      role: 'courier', 
      status: 'COURIER_ASSIGNED,PICKED_UP' 
    }],
    enabled: isAuthenticated && !!user?.id
  });

  // Fetch courier stats
  const { data: stats } = useQuery({
    queryKey: ['/api/courier/stats', user.id],
    initialData: {
      todayDeliveries: 14,
      todayEarnings: 28500,
      weeklyEarnings: 165000,
      monthlyEarnings: 680000,
      rating: 4.8,
      completionRate: 96,
      avgDeliveryTime: 25,
      totalDistance: 145,
      fuelCost: 15000,
      efficiency: 92
    }
  });

  return (
    <div className="container mx-auto p-4 space-y-6" data-testid="enhanced-courier-dashboard">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold text-primary flex items-center gap-2">
            <Truck className="h-8 w-8" />
            Dashboard Livreur Pro
          </h1>
          <p className="text-muted-foreground">
            <span className="font-medium">{user.name}</span> • 
            Optimisation intelligente des livraisons
          </p>
        </div>
        
        <div className="flex items-center gap-4">
          <div className="flex items-center space-x-2">
            <Switch
              id="availability"
              checked={isAvailable}
              onCheckedChange={setIsAvailable}
            />
            <label htmlFor="availability" className="text-sm font-medium">
              {isAvailable ? (
                <Badge className="bg-green-100 text-green-800">En ligne</Badge>
              ) : (
                <Badge className="bg-red-100 text-red-800">Hors ligne</Badge>
              )}
            </label>
          </div>
          
          {!courierData.verified && (
            <Alert className="max-w-sm">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription className="text-sm">
                <strong>Vérification requise</strong> - Validez votre profil livreur
              </AlertDescription>
            </Alert>
          )}
        </div>
      </div>

      {/* Real-time Performance Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="bg-gradient-to-br from-blue-600 to-blue-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-blue-100 text-sm">Gains aujourd'hui</p>
                <p className="text-2xl font-bold">
                  {(stats.todayEarnings / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-blue-200 mt-1">
                  {stats.todayDeliveries} livraisons
                </p>
              </div>
              <DollarSign className="h-8 w-8 text-blue-200" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-green-600 to-green-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-green-100 text-sm">Cette semaine</p>
                <p className="text-2xl font-bold">
                  {(stats.weeklyEarnings / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-green-200 mt-1">
                  +15% vs sem. passée
                </p>
              </div>
              <TrendingUp className="h-8 w-8 text-green-200" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-purple-600 to-purple-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-purple-100 text-sm">Note satisfaction</p>
                <p className="text-2xl font-bold flex items-center">
                  {stats.rating}
                  <Star className="h-5 w-5 ml-1 fill-current" />
                </p>
                <p className="text-xs text-purple-200 mt-1">
                  {stats.completionRate}% réussite
                </p>
              </div>
              <Award className="h-8 w-8 text-purple-200" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-orange-600 to-orange-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-orange-100 text-sm">Efficacité</p>
                <p className="text-2xl font-bold">{stats.efficiency}%</p>
                <p className="text-xs text-orange-200 mt-1">
                  {stats.avgDeliveryTime}min moy/livraison
                </p>
              </div>
              <Activity className="h-8 w-8 text-orange-200" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Active Delivery Alert */}
      {activeDeliveries.length > 0 && (
        <Alert className="border-blue-200 bg-gradient-to-r from-blue-50 to-indigo-50">
          <Navigation className="h-4 w-4 text-blue-600" />
          <AlertDescription>
            <strong>Livraison en cours!</strong> Vous avez {activeDeliveries.length} livraison(s) active(s). 
            Utilisez l'onglet "Itinéraires" pour optimiser votre parcours.
          </AlertDescription>
        </Alert>
      )}

      {/* Availability Status */}
      {!isAvailable && (
        <Alert className="border-gray-200 bg-gray-50">
          <Clock className="h-4 w-4 text-gray-600" />
          <AlertDescription>
            Vous êtes actuellement <strong>hors ligne</strong>. 
            Activez votre statut pour recevoir de nouvelles commandes.
          </AlertDescription>
        </Alert>
      )}

      {/* Main Content Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-5 bg-gray-100/50 p-1 rounded-lg">
          <TabsTrigger 
            value="overview" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Activity className="h-4 w-4" />
            Vue d'ensemble
          </TabsTrigger>
          <TabsTrigger 
            value="routes" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Navigation className="h-4 w-4" />
            Itinéraires
            {availableOrders.length > 0 && (
              <Badge variant="destructive" className="ml-1 px-1.5 py-0.5 text-xs">
                {availableOrders.length}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger 
            value="earnings" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <DollarSign className="h-4 w-4" />
            Revenus
          </TabsTrigger>
          <TabsTrigger 
            value="deliveries" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Package className="h-4 w-4" />
            Livraisons
          </TabsTrigger>
          <TabsTrigger 
            value="performance" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Target className="h-4 w-4" />
            Performance
          </TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          {/* Quick Stats Grid */}
          <div className="grid md:grid-cols-3 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Performance du jour</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Livraisons complétées</span>
                    <Badge variant="secondary">{stats.todayDeliveries}</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Distance parcourue</span>
                    <Badge variant="secondary">{stats.totalDistance} km</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Coût carburant</span>
                    <Badge variant="outline" className="text-red-600">
                      {(stats.fuelCost / 1000).toFixed(0)}k F
                    </Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Gain net</span>
                    <Badge className="bg-green-100 text-green-800">
                      {((stats.todayEarnings - stats.fuelCost) / 1000).toFixed(0)}k F
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Objectifs mensuels</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <div className="flex items-center justify-between text-sm mb-2">
                      <span>Revenus (800k F)</span>
                      <span>{(stats.monthlyEarnings / 1000).toFixed(0)}k F</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full" 
                        style={{ width: `${(stats.monthlyEarnings / 800000) * 100}%` }}
                      ></div>
                    </div>
                    <p className="text-xs text-muted-foreground mt-1">
                      {((stats.monthlyEarnings / 800000) * 100).toFixed(1)}% atteint
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Actions Rapides</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('routes')}
                >
                  <Navigation className="h-4 w-4 mr-2" />
                  Optimiser itinéraires
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('earnings')}
                >
                  <DollarSign className="h-4 w-4 mr-2" />
                  Voir les revenus
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('deliveries')}
                >
                  <Package className="h-4 w-4 mr-2" />
                  Historique livraisons
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('performance')}
                >
                  <Target className="h-4 w-4 mr-2" />
                  Analytics performance
                </Button>
              </CardContent>
            </Card>
          </div>

          {/* Available Orders Preview */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <Package className="h-5 w-5" />
                  Commandes disponibles
                </CardTitle>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => setActiveTab('routes')}
                >
                  Optimiser itinéraire
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {!isAvailable ? (
                <div className="text-center py-8">
                  <Clock className="h-16 w-16 mx-auto text-gray-300 mb-4" />
                  <h3 className="text-lg font-medium text-gray-600 mb-2">Hors ligne</h3>
                  <p className="text-muted-foreground mb-4">
                    Activez votre statut pour voir les commandes disponibles
                  </p>
                  <Button onClick={() => setIsAvailable(true)}>
                    <CheckCircle className="mr-2 h-4 w-4" />
                    Se mettre en ligne
                  </Button>
                </div>
              ) : loadingAvailable ? (
                <div className="text-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
                  <p className="mt-2 text-muted-foreground">Recherche de commandes...</p>
                </div>
              ) : availableOrders.length === 0 ? (
                <div className="text-center py-8">
                  <Package className="h-16 w-16 mx-auto text-gray-300 mb-4" />
                  <h3 className="text-lg font-medium text-gray-600 mb-2">Aucune commande disponible</h3>
                  <p className="text-muted-foreground">
                    Pas de nouvelles commandes dans votre zone pour le moment
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {availableOrders.slice(0, 3).map((order) => (
                    <div key={order.id} className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50">
                      <div className="flex items-center gap-3">
                        <MapPin className="h-4 w-4 text-primary" />
                        <div>
                          <p className="font-medium">#{order.id.slice(0, 8)}</p>
                          <p className="text-sm text-muted-foreground">{order.distanceKm} km • {order.medicineName}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        <Badge variant="secondary">
                          {((order.serviceFee || 0) + (order.deliveryFee || 0))} F
                        </Badge>
                        <Button variant="ghost" size="sm">
                          <Navigation className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                  {availableOrders.length > 3 && (
                    <div className="text-center pt-2">
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => setActiveTab('routes')}
                      >
                        Voir toutes ({availableOrders.length})
                      </Button>
                    </div>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Routes Tab */}
        <TabsContent value="routes" className="space-y-6">
          <CourierRouteOptimization courierId={user.id} />
        </TabsContent>

        {/* Earnings Tab */}
        <TabsContent value="earnings" className="space-y-6">
          <CourierEarningsDashboard courierId={user.id} />
        </TabsContent>

        {/* Deliveries Tab */}
        <TabsContent value="deliveries" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <History className="h-5 w-5" />
                Historique des Livraisons
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-center py-12">
                <Package className="h-16 w-16 mx-auto text-gray-300 mb-4" />
                <h3 className="text-lg font-medium text-gray-600 mb-2">Historique en cours de développement</h3>
                <p className="text-muted-foreground">
                  Cette fonctionnalité sera bientôt disponible
                </p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Performance Tab */}
        <TabsContent value="performance" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Target className="h-5 w-5" />
                Analytics de Performance
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid md:grid-cols-3 gap-6">
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-3xl font-bold text-green-600 mb-2">
                    {stats.completionRate}%
                  </div>
                  <p className="text-sm text-muted-foreground">Taux de réussite</p>
                  <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                    <div 
                      className="bg-green-600 h-2 rounded-full" 
                      style={{ width: `${stats.completionRate}%` }}
                    ></div>
                  </div>
                </div>
                
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-3xl font-bold text-blue-600 mb-2">
                    {stats.avgDeliveryTime}min
                  </div>
                  <p className="text-sm text-muted-foreground">Temps moyen/livraison</p>
                  <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full" 
                      style={{ width: '85%' }}
                    ></div>
                  </div>
                  <p className="text-xs text-green-600 mt-1">-3min ce mois</p>
                </div>
                
                <div className="text-center p-4 border rounded-lg">
                  <div className="text-3xl font-bold text-purple-600 mb-2">
                    {stats.efficiency}%
                  </div>
                  <p className="text-sm text-muted-foreground">Efficacité globale</p>
                  <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                    <div 
                      className="bg-purple-600 h-2 rounded-full" 
                      style={{ width: `${stats.efficiency}%` }}
                    ></div>
                  </div>
                  <p className="text-xs text-green-600 mt-1">Top 10%</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}