import { useState } from 'react';
import { Users, ShoppingBag, Building, Truck, TrendingUp, TrendingDown, Activity, CheckCircle, XCircle, Clock, AlertTriangle, Eye, Edit, UserCheck, UserX, MapPin, BarChart3, Settings, Monitor, Search, Filter, Download, RefreshCw } from 'lucide-react';
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';
import { apiRequest } from '@/lib/queryClient';

interface AdminStats {
  users: {
    total: number;
    byRole: Record<string, number>;
  };
  orders: {
    total: number;
    byStatus: Record<string, number>;
  };
  finance: {
    totalAmount: number;
    totalTransactions: number;
  };
  pharmacies: {
    verified: number;
    unverified: number;
  };
}

interface OrdersStats {
  today: number;
  thisWeek: number;
  thisMonth: number;
}

interface FinancialStats {
  revenue: number;
  earnings: number;
}

interface AdminUser {
  id: string;
  name: string;
  email: string;
  phone: string;
  role: string;
  isActive: boolean;
  verified: boolean;
  createdAt: string;
  pharmacy?: {
    id: string;
    name: string;
    address: string;
    verified: boolean;
  };
  courier?: {
    id: string;
    verified: boolean;
    vehicleType: string;
  };
}

interface ActivityItem {
  id: string;
  type: string;
  description: string;
  createdAt: string;
  status: string;
  clientName: string;
}

export function AdminDashboard() {
  const [selectedTab, setSelectedTab] = useState('overview');
  const [userFilters, setUserFilters] = useState({ role: '', verified: '' });
  const { toast } = useToast();
  const queryClient = useQueryClient();

  // Get admin statistics
  const { data: stats, isLoading: isLoadingStats } = useQuery<AdminStats>({
    queryKey: ['/api/admin/stats'],
    staleTime: 2 * 60 * 1000, // 2 minutes
  });

  // Get all users
  const { data: users = [], isLoading: isLoadingUsers } = useQuery<AdminUser[]>({
    queryKey: ['/api/admin/users', userFilters],
    staleTime: 60 * 1000, // 1 minute
  });

  // Get orders stats
  const { data: ordersStats = { today: 0, thisWeek: 0, thisMonth: 0 } } = useQuery<OrdersStats>({
    queryKey: ['/api/admin/orders/stats'],
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Get financial stats
  const { data: financialStats = { revenue: 0, earnings: 0 } } = useQuery<FinancialStats>({
    queryKey: ['/api/admin/financial/stats'],
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Get recent activity
  const { data: recentActivity = [] } = useQuery<ActivityItem[]>({
    queryKey: ['/api/admin/activity'],
    staleTime: 30 * 1000, // 30 seconds
  });

  // Verify user mutation
  const verifyUserMutation = useMutation({
    mutationFn: async ({ userId, verified }: { userId: string; verified: boolean }) => {
      return apiRequest(`/api/admin/users/${userId}/verify`, 'PUT', { verified });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/admin/users'] });
      queryClient.invalidateQueries({ queryKey: ['/api/admin/stats'] });
      toast({
        title: "Utilisateur mis à jour",
        description: "Le statut de vérification a été mis à jour",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de la mise à jour",
        variant: "destructive",
      });
    },
  });

  // Update user status mutation
  const updateUserStatusMutation = useMutation({
    mutationFn: async ({ userId, active }: { userId: string; active: boolean }) => {
      return apiRequest(`/api/admin/users/${userId}/status`, 'PUT', { active });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/admin/users'] });
      toast({
        title: "Statut mis à jour",
        description: "Le statut de l'utilisateur a été mis à jour",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Erreur",
        description: error.message || "Erreur lors de la mise à jour",
        variant: "destructive",
      });
    },
  });

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const formatAmount = (amount: number) => {
    return `${Math.abs(amount).toLocaleString()} FCFA`;
  };

  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin': return 'bg-purple-100 text-purple-800';
      case 'pharmacy': return 'bg-blue-100 text-blue-800';
      case 'courier': return 'bg-green-100 text-green-800';
      case 'client': return 'bg-gray-100 text-gray-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'DELIVERED': return 'bg-green-100 text-green-800';
      case 'CREATED': return 'bg-blue-100 text-blue-800';
      case 'CONFIRMED': return 'bg-yellow-100 text-yellow-800';
      case 'CANCELLED': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'order': return <ShoppingBag className="h-4 w-4" />;
      case 'user': return <Users className="h-4 w-4" />;
      default: return <Activity className="h-4 w-4" />;
    }
  };

  if (isLoadingStats) {
    return (
      <div className="flex items-center justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6" data-testid="admin-dashboard">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Dashboard Administrateur</h1>
        <p className="text-gray-600">Gestion et supervision de la plateforme MediFlash SOS+</p>
      </div>

      <Tabs value={selectedTab} onValueChange={setSelectedTab} className="w-full">
        <TabsList className="grid w-full grid-cols-7">
          <TabsTrigger value="overview">Vue d'ensemble</TabsTrigger>
          <TabsTrigger value="users">Utilisateurs</TabsTrigger>
          <TabsTrigger value="orders">Commandes</TabsTrigger>
          <TabsTrigger value="pharmacies">Pharmacies</TabsTrigger>
          <TabsTrigger value="analytics">Analytiques</TabsTrigger>
          <TabsTrigger value="config">Configuration</TabsTrigger>
          <TabsTrigger value="monitoring">Monitoring</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-6">
          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Users className="h-8 w-8 text-blue-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Utilisateurs Total</p>
                    <p className="text-2xl font-bold" data-testid="total-users">
                      {stats?.users.total || 0}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <ShoppingBag className="h-8 w-8 text-green-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Commandes Total</p>
                    <p className="text-2xl font-bold" data-testid="total-orders">
                      {stats?.orders.total || 0}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Building className="h-8 w-8 text-purple-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Pharmacies Vérifiées</p>
                    <p className="text-2xl font-bold" data-testid="verified-pharmacies">
                      {stats?.pharmacies.verified || 0}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <TrendingUp className="h-8 w-8 text-yellow-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Volume Transactions</p>
                    <p className="text-2xl font-bold" data-testid="total-transactions">
                      {formatAmount(stats?.finance.totalAmount || 0)}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Charts and Recent Activity */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Users by Role */}
            <Card>
              <CardHeader>
                <CardTitle>Répartition des utilisateurs</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {Object.entries(stats?.users.byRole || {}).map(([role, count]) => (
                    <div key={role} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Badge className={getRoleColor(role)}>
                          {role === 'client' ? 'Clients' : 
                           role === 'pharmacy' ? 'Pharmacies' :
                           role === 'courier' ? 'Livreurs' : 'Admins'}
                        </Badge>
                      </div>
                      <span className="font-semibold">{count}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Recent Activity */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="h-5 w-5" />
                  Activité récente
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3 max-h-64 overflow-y-auto">
                  {recentActivity.map((item) => (
                    <div key={`${item.type}-${item.id}`} className="flex items-start gap-3 text-sm">
                      <div className="flex-shrink-0 mt-0.5">
                        {getActivityIcon(item.type)}
                      </div>
                      <div className="flex-1">
                        <p className="text-gray-900">{item.description}</p>
                        <p className="text-gray-500 text-xs">{formatDate(item.createdAt)}</p>
                      </div>
                      <Badge className={getStatusColor(item.status)} variant="outline">
                        {item.status}
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Quick Actions */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Card className="border-yellow-200 bg-yellow-50">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <AlertTriangle className="h-8 w-8 text-yellow-600" />
                  <div>
                    <h3 className="font-semibold text-yellow-800">Pharmacies en attente</h3>
                    <p className="text-sm text-yellow-700">{stats?.pharmacies.unverified || 0} à vérifier</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-blue-200 bg-blue-50">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <ShoppingBag className="h-8 w-8 text-blue-600" />
                  <div>
                    <h3 className="font-semibold text-blue-800">Commandes aujourd'hui</h3>
                    <p className="text-sm text-blue-700">{ordersStats?.today || 0} nouvelles</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-green-200 bg-green-50">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <TrendingUp className="h-8 w-8 text-green-600" />
                  <div>
                    <h3 className="font-semibold text-green-800">Revenus ce mois</h3>
                    <p className="text-sm text-green-700">{formatAmount(financialStats?.revenue || 0)}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="users" className="space-y-6">
          {/* User Management */}
          <Card>
            <CardHeader>
              <CardTitle>Gestion des utilisateurs</CardTitle>
              <div className="flex gap-4">
                <select
                  value={userFilters.role}
                  onChange={(e) => setUserFilters({ ...userFilters, role: e.target.value })}
                  className="px-3 py-2 border rounded-md"
                >
                  <option value="">Tous les rôles</option>
                  <option value="client">Clients</option>
                  <option value="pharmacy">Pharmacies</option>
                  <option value="courier">Livreurs</option>
                  <option value="admin">Admins</option>
                </select>
                <select
                  value={userFilters.verified}
                  onChange={(e) => setUserFilters({ ...userFilters, verified: e.target.value })}
                  className="px-3 py-2 border rounded-md"
                >
                  <option value="">Tous statuts</option>
                  <option value="true">Vérifiés</option>
                  <option value="false">Non vérifiés</option>
                </select>
              </div>
            </CardHeader>
            <CardContent>
              {isLoadingUsers ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-red-600"></div>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nom</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Rôle</TableHead>
                      <TableHead>Statut</TableHead>
                      <TableHead>Inscrit le</TableHead>
                      <TableHead>Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {users.map((user) => (
                      <TableRow key={user.id} data-testid={`user-row-${user.id}`}>
                        <TableCell className="font-medium">{user.name}</TableCell>
                        <TableCell>{user.email}</TableCell>
                        <TableCell>
                          <Badge className={getRoleColor(user.role)}>
                            {user.role}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            <Badge variant={user.isActive ? "default" : "secondary"}>
                              {user.isActive ? 'Actif' : 'Inactif'}
                            </Badge>
                            {(user.role === 'pharmacy' || user.role === 'courier') && (
                              <Badge variant={user.verified ? "default" : "destructive"}>
                                {user.verified ? 'Vérifié' : 'Non vérifié'}
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>{formatDate(user.createdAt)}</TableCell>
                        <TableCell>
                          <div className="flex gap-2">
                            {(user.role === 'pharmacy' || user.role === 'courier') && (
                              <Button
                                size="sm"
                                variant={user.verified ? "outline" : "default"}
                                onClick={() => verifyUserMutation.mutate({ userId: user.id, verified: !user.verified })}
                                disabled={verifyUserMutation.isPending}
                                data-testid={`verify-user-${user.id}`}
                              >
                                {user.verified ? <UserX className="h-4 w-4" /> : <UserCheck className="h-4 w-4" />}
                              </Button>
                            )}
                            <Button
                              size="sm"
                              variant={user.isActive ? "destructive" : "default"}
                              onClick={() => updateUserStatusMutation.mutate({ userId: user.id, active: !user.isActive })}
                              disabled={updateUserStatusMutation.isPending}
                              data-testid={`toggle-user-${user.id}`}
                            >
                              {user.isActive ? 'Désactiver' : 'Activer'}
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="orders" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Statistiques des commandes</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-3 gap-6">
                <div className="text-center">
                  <p className="text-sm text-gray-600">Aujourd'hui</p>
                  <p className="text-2xl font-bold">{ordersStats?.today || 0}</p>
                </div>
                <div className="text-center">
                  <p className="text-sm text-gray-600">Cette semaine</p>
                  <p className="text-2xl font-bold">{ordersStats?.thisWeek || 0}</p>
                </div>
                <div className="text-center">
                  <p className="text-sm text-gray-600">Ce mois</p>
                  <p className="text-2xl font-bold">{ordersStats?.thisMonth || 0}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Répartition par statut</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {Object.entries(stats?.orders.byStatus || {}).map(([status, count]) => (
                  <div key={status} className="flex items-center justify-between">
                    <Badge className={getStatusColor(status)}>
                      {status}
                    </Badge>
                    <span className="font-semibold">{count}</span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="finance" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="h-5 w-5 text-green-600" />
                  Revenus ce mois
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-3xl font-bold text-green-600">
                  {formatAmount(financialStats?.revenue || 0)}
                </p>
                <p className="text-sm text-gray-600 mt-2">
                  Commissions et frais de service
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingDown className="h-5 w-5 text-blue-600" />
                  Gains versés ce mois
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-3xl font-bold text-blue-600">
                  {formatAmount(financialStats?.earnings || 0)}
                </p>
                <p className="text-sm text-gray-600 mt-2">
                  Revenus pharmacies et livreurs
                </p>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Volume global des transactions</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <p className="text-sm text-gray-600">Montant total</p>
                  <p className="text-2xl font-bold">
                    {formatAmount(stats?.finance.totalAmount || 0)}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600">Nombre de transactions</p>
                  <p className="text-2xl font-bold">
                    {(stats?.finance.totalTransactions || 0).toLocaleString()}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== ONGLET PHARMACIES AVANCÉ ===== */}
        <TabsContent value="pharmacies" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Gestion Avancée des Pharmacies</h2>
              <p className="text-gray-600">Géolocalisation, stock, et vérifications</p>
            </div>
            <div className="flex gap-3">
              <Button variant="outline" size="sm">
                <MapPin className="h-4 w-4 mr-2" />
                Vue Carte
              </Button>
              <Button variant="outline" size="sm">
                <Download className="h-4 w-4 mr-2" />
                Exporter
              </Button>
            </div>
          </div>

          {/* Statistiques des Pharmacies */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Building className="h-8 w-8 text-blue-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Total Pharmacies</p>
                    <p className="text-2xl font-bold">
                      {(stats?.pharmacies.verified || 0) + (stats?.pharmacies.unverified || 0)}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <CheckCircle className="h-8 w-8 text-green-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Vérifiées</p>
                    <p className="text-2xl font-bold text-green-600">
                      {stats?.pharmacies.verified || 0}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <AlertTriangle className="h-8 w-8 text-yellow-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">En attente</p>
                    <p className="text-2xl font-bold text-yellow-600">
                      {stats?.pharmacies.unverified || 0}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Activity className="h-8 w-8 text-purple-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-gray-600">Actives aujourd'hui</p>
                    <p className="text-2xl font-bold text-purple-600">12</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Carte et filtres */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <Card className="lg:col-span-2">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <MapPin className="h-5 w-5" />
                  Répartition Géographique
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-64 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-600">Carte interactive des pharmacies</p>
                    <p className="text-sm text-gray-500">Intégration Leaflet.js</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Filtres Avancés</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-700">Statut</label>
                  <select className="w-full mt-1 px-3 py-2 border rounded-md">
                    <option>Toutes</option>
                    <option>Vérifiées</option>
                    <option>En attente</option>
                    <option>Suspendues</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700">Distance (km)</label>
                  <select className="w-full mt-1 px-3 py-2 border rounded-md">
                    <option>Toutes</option>
                    <option>≤ 5 km</option>
                    <option>5-15 km</option>
                    <option>&gt; 15 km</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700">Stock critique</label>
                  <select className="w-full mt-1 px-3 py-2 border rounded-md">
                    <option>Toutes</option>
                    <option>Stock bas</option>
                    <option>Rupture</option>
                  </select>
                </div>
                <Button className="w-full">
                  <Filter className="h-4 w-4 mr-2" />
                  Appliquer
                </Button>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* ===== ONGLET ANALYTIQUES AVANCÉES ===== */}
        <TabsContent value="analytics" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Analytiques Avancées</h2>
              <p className="text-gray-600">Rapports, métriques et insights</p>
            </div>
            <div className="flex gap-3">
              <Button variant="outline" size="sm">
                <RefreshCw className="h-4 w-4 mr-2" />
                Actualiser
              </Button>
              <Button variant="outline" size="sm">
                <Download className="h-4 w-4 mr-2" />
                Rapport PDF
              </Button>
            </div>
          </div>

          {/* KPI Cards */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Card className="bg-gradient-to-r from-blue-500 to-blue-600 text-white">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-blue-100">Taux de Conversion</p>
                    <p className="text-3xl font-bold">68.5%</p>
                    <p className="text-blue-200 text-sm">+5.2% ce mois</p>
                  </div>
                  <TrendingUp className="h-12 w-12 text-blue-200" />
                </div>
              </CardContent>
            </Card>

            <Card className="bg-gradient-to-r from-green-500 to-green-600 text-white">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-green-100">Temps Moy. Livraison</p>
                    <p className="text-3xl font-bold">23 min</p>
                    <p className="text-green-200 text-sm">-3 min ce mois</p>
                  </div>
                  <Clock className="h-12 w-12 text-green-200" />
                </div>
              </CardContent>
            </Card>

            <Card className="bg-gradient-to-r from-purple-500 to-purple-600 text-white">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-purple-100">Satisfaction Client</p>
                    <p className="text-3xl font-bold">4.8/5</p>
                    <p className="text-purple-200 text-sm">+0.2 ce mois</p>
                  </div>
                  <Activity className="h-12 w-12 text-purple-200" />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Graphiques */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BarChart3 className="h-5 w-5" />
                  Évolution des Commandes
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-64 bg-gray-50 rounded-lg flex items-center justify-center">
                  <div className="text-center">
                    <BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-gray-600">Graphique en barres</p>
                    <p className="text-sm text-gray-500">Évolution mensuelle</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="h-5 w-5" />
                  Revenus par Heure
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-64 bg-gray-50 rounded-lg flex items-center justify-center">
                  <div className="text-center">
                    <TrendingUp className="h-12 w-12 text-gray-400 mx-auto mb-2" />
                    <p className="text-gray-600">Graphique linéaire</p>
                    <p className="text-sm text-gray-500">Pics d'activité</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Top Médicaments */}
          <Card>
            <CardHeader>
              <CardTitle>Top Médicaments les Plus Demandés</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {[
                  { name: 'Paracétamol 500mg', count: 245, trend: '+12%' },
                  { name: 'Ibuprofène 400mg', count: 189, trend: '+8%' },
                  { name: 'Amoxicilline 1g', count: 156, trend: '+15%' },
                  { name: 'Doliprane 1000mg', count: 134, trend: '+3%' },
                  { name: 'Spasfon', count: 98, trend: '-2%' }
                ].map((med, index) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center text-blue-600 font-bold text-sm">
                        {index + 1}
                      </div>
                      <div>
                        <p className="font-medium">{med.name}</p>
                        <p className="text-sm text-gray-600">{med.count} demandes</p>
                      </div>
                    </div>
                    <Badge className={med.trend.startsWith('+') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                      {med.trend}
                    </Badge>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== ONGLET CONFIGURATION SYSTÈME ===== */}
        <TabsContent value="config" className="space-y-6">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">Configuration Système</h2>
            <p className="text-gray-600">Paramètres globaux et configuration de la plateforme</p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Paramètres Généraux */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Settings className="h-5 w-5" />
                  Paramètres Généraux
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-700">Frais de Service (FCFA)</label>
                  <input 
                    type="number" 
                    defaultValue="500" 
                    className="w-full mt-1 px-3 py-2 border rounded-md focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700">Distance Max Livraison (km)</label>
                  <input 
                    type="number" 
                    defaultValue="15" 
                    className="w-full mt-1 px-3 py-2 border rounded-md focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700">Temps Max Livraison (min)</label>
                  <input 
                    type="number" 
                    defaultValue="45" 
                    className="w-full mt-1 px-3 py-2 border rounded-md focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700">Mode Maintenance</label>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </CardContent>
            </Card>

            {/* Notifications */}
            <Card>
              <CardHeader>
                <CardTitle>Notifications Système</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700">Notifications Email</label>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" defaultChecked className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700">Notifications Push</label>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" defaultChecked className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700">Alertes Stock Bas</label>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" defaultChecked className="sr-only peer" />
                    <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Actions Système */}
          <Card>
            <CardHeader>
              <CardTitle>Actions Système</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <Button variant="outline" className="h-20">
                  <div className="text-center">
                    <RefreshCw className="h-6 w-6 mx-auto mb-2" />
                    <p className="text-sm">Vider Cache</p>
                  </div>
                </Button>
                <Button variant="outline" className="h-20">
                  <div className="text-center">
                    <Download className="h-6 w-6 mx-auto mb-2" />
                    <p className="text-sm">Backup BD</p>
                  </div>
                </Button>
                <Button variant="outline" className="h-20">
                  <div className="text-center">
                    <Activity className="h-6 w-6 mx-auto mb-2" />
                    <p className="text-sm">Log Système</p>
                  </div>
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ===== ONGLET MONITORING TEMPS RÉEL ===== */}
        <TabsContent value="monitoring" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Monitoring Temps Réel</h2>
              <p className="text-gray-600">Surveillance système et performance en direct</p>
            </div>
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                <span className="text-sm font-medium text-green-600">Système Opérationnel</span>
              </div>
              <Button variant="outline" size="sm">
                <RefreshCw className="h-4 w-4 mr-2" />
                Actualiser
              </Button>
            </div>
          </div>

          {/* Métriques Temps Réel */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <Card className="border-green-200 bg-green-50">
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Monitor className="h-8 w-8 text-green-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-green-600">Commandes Actives</p>
                    <p className="text-2xl font-bold text-green-700">24</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-blue-200 bg-blue-50">
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Users className="h-8 w-8 text-blue-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-blue-600">Utilisateurs Connectés</p>
                    <p className="text-2xl font-bold text-blue-700">147</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-yellow-200 bg-yellow-50">
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Truck className="h-8 w-8 text-yellow-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-yellow-600">Coursiers Actifs</p>
                    <p className="text-2xl font-bold text-yellow-700">8</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="border-purple-200 bg-purple-50">
              <CardContent className="p-6">
                <div className="flex items-center">
                  <Activity className="h-8 w-8 text-purple-600" />
                  <div className="ml-4">
                    <p className="text-sm font-medium text-purple-600">Charge Serveur</p>
                    <p className="text-2xl font-bold text-purple-700">23%</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Logs et Activité Récente */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="h-5 w-5" />
                  Activité en Direct
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3 max-h-64 overflow-y-auto">
                  {[
                    { time: '09:23:45', action: 'Nouvelle commande #1234', status: 'success' },
                    { time: '09:22:31', action: 'Coursier connecté: Jean Martin', status: 'info' },
                    { time: '09:21:12', action: 'Livraison terminée #1230', status: 'success' },
                    { time: '09:20:05', action: 'Pharmacie Dupont - Stock bas', status: 'warning' },
                    { time: '09:19:33', action: 'Nouveau client inscrit', status: 'info' }
                  ].map((log, index) => (
                    <div key={index} className="flex items-center justify-between text-sm">
                      <div className="flex items-center gap-3">
                        <span className="text-gray-500 font-mono">{log.time}</span>
                        <span>{log.action}</span>
                      </div>
                      <Badge className={
                        log.status === 'success' ? 'bg-green-100 text-green-800' :
                        log.status === 'warning' ? 'bg-yellow-100 text-yellow-800' :
                        'bg-blue-100 text-blue-800'
                      }>
                        {log.status}
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Performance Système</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span>CPU Usage</span>
                      <span>23%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div className="bg-blue-600 h-2 rounded-full" style={{ width: '23%' }}></div>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span>RAM Usage</span>
                      <span>67%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div className="bg-green-600 h-2 rounded-full" style={{ width: '67%' }}></div>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span>Stockage</span>
                      <span>34%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div className="bg-yellow-600 h-2 rounded-full" style={{ width: '34%' }}></div>
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span>Bande Passante</span>
                      <span>12%</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div className="bg-purple-600 h-2 rounded-full" style={{ width: '12%' }}></div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}