/**
 * Dashboard Administrateur Optimisé avec Performances
 * Version haute performance avec lazy loading, memoization et cache intelligent
 */

import React, { memo, useState, useCallback, useMemo } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useOptimizedQuery, usePaginatedQuery, useStaticQuery } from '@/hooks/useOptimizedQuery';
import { usePerformanceMetrics, PerformanceMonitor, useRenderTracker } from '@/components/performance/PerformanceMonitor';
import { LazyTable, LazyTableColumn } from '@/components/optimized/LazyTable';
import { StatsCard, ActionCard, ListItemCard } from '@/components/optimized/MemoizedCard';
import VirtualizedList from '@/components/optimized/VirtualizedList';
import { Users, ShoppingBag, Building, Truck, TrendingUp, Activity, Settings, Monitor, MapPin, BarChart3, RefreshCw, Download, UserCheck, UserX } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';
import { apiRequest } from '@/lib/queryClient';

// Types optimisés
interface OptimizedAdminStats {
  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 OptimizedAdminUser {
  id: string;
  name: string;
  email: string;
  phone: string;
  role: string;
  active: boolean;
  verified: boolean;
  createdAt: string;
  pharmacy?: any;
  courier?: any;
}

interface PaginationParams {
  page: number;
  limit: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
  role?: string;
  verified?: string;
}

// Composant principal optimisé
export const OptimizedAdminDashboard = memo(() => {
  const [selectedTab, setSelectedTab] = useState('overview');
  const [userFilters, setUserFilters] = useState<Omit<PaginationParams, 'page' | 'limit'>>({
    role: '',
    verified: '',
    sortBy: 'createdAt',
    sortOrder: 'desc'
  });
  const [userPagination, setUserPagination] = useState({ page: 1, limit: 20 });
  
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { recordApiCall, recordCacheHit } = usePerformanceMetrics();
  
  // Tracker des re-renders pour le debugging
  useRenderTracker('OptimizedAdminDashboard');

  // Statistiques admin avec cache long (stratégie static)
  const { data: stats, isLoading: isLoadingStats } = useStaticQuery<OptimizedAdminStats>({
    queryKey: ['admin', 'stats'],
    queryFn: async () => {
      const start = Date.now();
      const result = await apiRequest('/api/admin/stats');
      recordApiCall(Date.now() - start);
      return result;
    }
  });

  // Utilisateurs avec pagination optimisée
  const {
    data: usersData,
    isLoading: isLoadingUsers,
    error: usersError
  } = usePaginatedQuery(
    ['admin', 'users'],
    async (params: PaginationParams) => {
      const start = Date.now();
      const searchParams = new URLSearchParams({
        page: params.page.toString(),
        limit: params.limit.toString(),
        ...(params.role && { role: params.role }),
        ...(params.verified && { verified: params.verified }),
        ...(params.sortBy && { sortBy: params.sortBy }),
        ...(params.sortOrder && { sortOrder: params.sortOrder })
      });
      
      const result = await apiRequest(`/api/admin/users/paginated?${searchParams}`);
      recordApiCall(Date.now() - start);
      return result;
    },
    { ...userPagination, ...userFilters }
  );

  // Statistiques temps réel avec cache court
  const { data: realtimeStats } = useOptimizedQuery({
    queryKey: ['admin', 'realtime'],
    queryFn: async () => {
      const result = await Promise.all([
        apiRequest('/api/admin/orders/stats'),
        apiRequest('/api/admin/financial/stats'),
        apiRequest('/api/admin/activity')
      ]);
      return {
        orders: result[0],
        financial: result[1],
        activity: result[2]
      };
    },
    cacheStrategy: 'realtime'
  });

  // Mutations optimisées avec cache invalidation intelligente
  const verifyUserMutation = useMutation({
    mutationFn: async ({ userId, verified }: { userId: string; verified: boolean }) => {
      const start = Date.now();
      const result = await apiRequest(`/api/admin/users/${userId}/verify`, 'PUT', { verified });
      recordApiCall(Date.now() - start);
      return result;
    },
    onSuccess: () => {
      // Invalidation ciblée du cache
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
      queryClient.invalidateQueries({ queryKey: ['admin', 'stats'] });
      toast({
        title: "Utilisateur mis à jour",
        description: "Le statut de vérification a été mis à jour",
      });
    }
  });

  const updateUserStatusMutation = useMutation({
    mutationFn: async ({ userId, active }: { userId: string; active: boolean }) => {
      return apiRequest(`/api/admin/users/${userId}/status`, 'PUT', { active });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
      toast({ title: "Statut mis à jour" });
    }
  });

  // Callbacks mémorisés
  const handlePageChange = useCallback((page: number) => {
    setUserPagination(prev => ({ ...prev, page }));
  }, []);

  const handleFilterChange = useCallback((filters: Partial<typeof userFilters>) => {
    setUserFilters(prev => ({ ...prev, ...filters }));
    setUserPagination(prev => ({ ...prev, page: 1 })); // Reset page
  }, []);

  // Configuration des colonnes pour la table optimisée
  const userTableColumns = useMemo((): LazyTableColumn<OptimizedAdminUser>[] => [
    {
      key: 'name',
      header: 'Nom',
      sortable: true,
      render: (value, user) => (
        <div>
          <div className="font-medium">{value}</div>
          <div className="text-sm text-gray-500">{user.email}</div>
        </div>
      )
    },
    {
      key: 'role',
      header: 'Rôle',
      sortable: true,
      render: (value) => (
        <span className={`px-2 py-1 rounded text-xs ${
          value === 'admin' ? 'bg-purple-100 text-purple-800' :
          value === 'pharmacy' ? 'bg-blue-100 text-blue-800' :
          value === 'courier' ? 'bg-green-100 text-green-800' :
          'bg-gray-100 text-gray-800'
        }`}>
          {value}
        </span>
      )
    },
    {
      key: 'active',
      header: 'Statut',
      render: (active, user) => (
        <div className="flex gap-1">
          <span className={`px-2 py-1 rounded text-xs ${
            active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
          }`}>
            {active ? 'Actif' : 'Inactif'}
          </span>
          {(user.role === 'pharmacy' || user.role === 'courier') && (
            <span className={`px-2 py-1 rounded text-xs ${
              user.verified ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
            }`}>
              {user.verified ? 'Vérifié' : 'Non vérifié'}
            </span>
          )}
        </div>
      )
    },
    {
      key: 'createdAt',
      header: 'Inscription',
      sortable: true,
      render: (value) => new Date(value).toLocaleDateString('fr-FR')
    },
    {
      key: 'id',
      header: 'Actions',
      render: (_, user) => (
        <div className="flex gap-1">
          {(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}
            >
              {user.verified ? <UserX className="h-3 w-3" /> : <UserCheck className="h-3 w-3" />}
            </Button>
          )}
          <Button
            size="sm"
            variant={user.active ? "destructive" : "default"}
            onClick={() => updateUserStatusMutation.mutate({ 
              userId: user.id, 
              active: !user.active 
            })}
            disabled={updateUserStatusMutation.isPending}
          >
            {user.active ? 'Désactiver' : 'Activer'}
          </Button>
        </div>
      )
    }
  ], [verifyUserMutation, updateUserStatusMutation]);

  // Stats cards mémorisées
  const statsCards = useMemo(() => {
    if (!stats) return [];
    
    return [
      {
        title: 'Utilisateurs Total',
        value: stats.users.total,
        icon: Users,
        iconColor: 'text-blue-600',
        trend: { value: '+12%', isPositive: true }
      },
      {
        title: 'Commandes Total',
        value: stats.orders.total,
        icon: ShoppingBag,
        iconColor: 'text-green-600',
        trend: { value: '+8%', isPositive: true }
      },
      {
        title: 'Pharmacies Vérifiées',
        value: stats.pharmacies.verified,
        icon: Building,
        iconColor: 'text-purple-600'
      },
      {
        title: 'Volume Transactions',
        value: `${Math.abs(stats.finance.totalAmount).toLocaleString()} FCFA`,
        icon: TrendingUp,
        iconColor: 'text-yellow-600',
        trend: { value: '+15%', isPositive: true }
      }
    ];
  }, [stats]);

  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-blue-600"></div>
        <span className="ml-2">Chargement des données...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6" data-testid="optimized-admin-dashboard">
      {/* Moniteur de performance (compact) */}
      <PerformanceMonitor compact className="mb-4" />
      
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">
            Dashboard Administrateur Optimisé
          </h1>
          <p className="text-gray-600">
            Gestion haute performance de MediFlash SOS+
          </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" />
            Exporter
          </Button>
        </div>
      </div>

      <Tabs value={selectedTab} onValueChange={setSelectedTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">Vue d'ensemble</TabsTrigger>
          <TabsTrigger value="users">Utilisateurs</TabsTrigger>
          <TabsTrigger value="analytics">Analytiques</TabsTrigger>
          <TabsTrigger value="performance">Performance</TabsTrigger>
        </TabsList>

        {/* Vue d'ensemble avec cards optimisées */}
        <TabsContent value="overview" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {statsCards.map((card, index) => (
              <StatsCard
                key={index}
                title={card.title}
                value={card.value}
                icon={card.icon}
                iconColor={card.iconColor}
                trend={card.trend}
                loading={isLoadingStats}
              />
            ))}
          </div>

          {/* Actions rapides */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <ActionCard
              title="Pharmacies en attente"
              description={`${stats?.pharmacies.unverified || 0} pharmacies à vérifier`}
              icon={Building}
              iconColor="text-yellow-600"
              bgColor="bg-yellow-50 border-yellow-200"
              actions={[
                {
                  label: 'Voir tout',
                  onClick: () => setSelectedTab('users'),
                  variant: 'default'
                }
              ]}
            />
            
            <ActionCard
              title="Performance système"
              description="Surveillance temps réel active"
              icon={Monitor}
              iconColor="text-green-600"
              bgColor="bg-green-50 border-green-200"
              actions={[
                {
                  label: 'Détails',
                  onClick: () => setSelectedTab('performance'),
                  variant: 'outline'
                }
              ]}
            />
            
            <ActionCard
              title="Analytiques avancées"
              description="Rapports et insights disponibles"
              icon={BarChart3}
              iconColor="text-blue-600"
              bgColor="bg-blue-50 border-blue-200"
              actions={[
                {
                  label: 'Analyser',
                  onClick: () => setSelectedTab('analytics'),
                  variant: 'default'
                }
              ]}
            />
          </div>
        </TabsContent>

        {/* Gestion utilisateurs avec table optimisée */}
        <TabsContent value="users" className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-2xl font-bold">Gestion Utilisateurs Optimisée</h2>
            <div className="flex gap-3">
              <select
                value={userFilters.role}
                onChange={(e) => handleFilterChange({ 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) => handleFilterChange({ 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>
          </div>

          <LazyTable
            data={usersData?.data || []}
            columns={userTableColumns}
            loading={isLoadingUsers}
            pagination={usersData?.pagination}
            onPageChange={handlePageChange}
            loadingRows={10}
            maxHeight="600px"
            emptyMessage="Aucun utilisateur trouvé"
          />
        </TabsContent>

        {/* Analytiques */}
        <TabsContent value="analytics" className="space-y-6">
          <h2 className="text-2xl font-bold">Analytiques Avancées</h2>
          <div className="text-gray-600">
            Fonctionnalités analytiques optimisées en cours de développement...
          </div>
        </TabsContent>

        {/* Performance */}
        <TabsContent value="performance" className="space-y-6">
          <h2 className="text-2xl font-bold">Monitoring Performance</h2>
          <PerformanceMonitor showAlerts={true} />
        </TabsContent>
      </Tabs>
    </div>
  );
});

OptimizedAdminDashboard.displayName = 'OptimizedAdminDashboard';

export default OptimizedAdminDashboard;