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 { Alert, AlertDescription } from '@/components/ui/alert';
import { SosFormWithMap } from '@/components/sos-form-with-map';
import { WalletDashboard } from '@/components/wallet-dashboard';
import { MedicalProfile } from '@/components/medical-profile';
import { ClientAnalytics } from '@/components/client-analytics';
import { ClientNotifications } from '@/components/client-notifications';
import { NotificationCenter, LiveStatusIndicator } from '@/components/real-time/NotificationCenter';
import { OrderTracker } from '@/components/real-time/OrderTracker';
import { ORDER_STATUSES } from '@/lib/constants';
import { OrderWithDetails } from '@shared/schema';
import { useAuth } from '@/contexts/AuthContext';
import {
  User,
  Plus,
  ShoppingBag,
  CheckCircle,
  Clock,
  TrendingUp,
  MapPin,
  Receipt,
  Pill,
  Phone,
  Eye,
  AlertCircle,
  Activity,
  Bell,
  Heart,
  BarChart3,
  Wallet
} from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

export function EnhancedClientDashboard() {
  const { user, isAuthenticated } = useAuth();
  const [showSosModal, setShowSosModal] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');

  // Fetch user's orders
  const { data: orders = [], isLoading } = useQuery<OrderWithDetails[]>({
    queryKey: ['/api/orders', { userId: user?.id, role: 'client' }],
    enabled: isAuthenticated && !!user?.id,
  });

  // Redirect if not authenticated or not a client
  if (!isAuthenticated || !user) {
    return (
      <div className="container mx-auto p-4">
        <Alert>
          <AlertDescription>
            Vous devez être connecté en tant que client pour accéder à cette page.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  if (user.role !== 'client') {
    return (
      <div className="container mx-auto p-4">
        <Alert>
          <AlertDescription>
            Cette page est réservée aux clients.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  // Calculate stats
  const stats = {
    total_orders: orders.length,
    delivered_orders: orders.filter(o => o.status === 'DELIVERED').length,
    active_orders: orders.filter(o => o.status && !['DELIVERED', 'CLOSED'].includes(o.status)).length,
    avg_delivery_time: '24min'
  };

  const getStatusBadge = (status: keyof typeof ORDER_STATUSES | null) => {
    if (!status) return <Badge className="bg-gray-500 text-white">Inconnu</Badge>;
    const config = ORDER_STATUSES[status];
    return (
      <Badge className={`${config.color} text-white`}>
        {config.label}
      </Badge>
    );
  };

  return (
    <div className="container mx-auto p-4 space-y-6" data-testid="enhanced-client-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">
            <User className="h-8 w-8" />
            Dashboard Client Avancé
          </h1>
          <p className="text-muted-foreground">
            Bienvenue <span className="font-medium">{user.name}</span> • 
            Gérez votre santé intelligemment
          </p>
        </div>
        
        <Dialog open={showSosModal} onOpenChange={setShowSosModal}>
          <DialogTrigger asChild>
            <Button 
              className="bg-gradient-to-r from-red-600 to-red-500 hover:from-red-700 hover:to-red-600 text-white font-medium shadow-lg"
              data-testid="button-new-sos"
            >
              <Plus className="mr-2 h-4 w-4" />
              SOS Urgence
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Nouvelle demande SOS</DialogTitle>
              <DialogDescription>
                Remplissez le formulaire pour une livraison d'urgence de médicaments
              </DialogDescription>
            </DialogHeader>
            <SosFormWithMap 
              onSuccess={(orderId) => {
                setShowSosModal(false);
                // Switch to tracking tab and refetch orders
                setActiveTab('tracking');
              }}
            />
          </DialogContent>
        </Dialog>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <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">Commandes totales</p>
                <p className="text-2xl font-bold">{stats.total_orders}</p>
                <p className="text-xs text-blue-200 mt-1">+12% ce mois</p>
              </div>
              <ShoppingBag className="h-8 w-8 opacity-75" />
            </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">Livrées</p>
                <p className="text-2xl font-bold">{stats.delivered_orders}</p>
                <p className="text-xs text-green-200 mt-1">98% succès</p>
              </div>
              <CheckCircle className="h-8 w-8 opacity-75" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-yellow-600 to-yellow-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-yellow-100 text-sm">En cours</p>
                <p className="text-2xl font-bold">{stats.active_orders}</p>
                <p className="text-xs text-yellow-200 mt-1">Suivi temps réel</p>
              </div>
              <Clock className="h-8 w-8 opacity-75" />
            </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">Temps moyen</p>
                <p className="text-2xl font-bold">{stats.avg_delivery_time}</p>
                <p className="text-xs text-purple-200 mt-1">-5min ce mois</p>
              </div>
              <TrendingUp className="h-8 w-8 opacity-75" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Active Orders Alert */}
      {stats.active_orders > 0 && (
        <Alert className="border-yellow-200 bg-gradient-to-r from-yellow-50 to-orange-50">
          <AlertCircle className="h-4 w-4 text-yellow-600" />
          <AlertDescription>
            Vous avez <strong>{stats.active_orders} commande(s) en cours</strong>. 
            Suivez leur progression en temps réel dans l'onglet "Mes Commandes".
          </AlertDescription>
        </Alert>
      )}

      {/* Live Status Indicator */}
      <div className="flex justify-end">
        <LiveStatusIndicator />
      </div>

      {/* Main Content Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-6 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"
          >
            <Eye className="h-4 w-4" />
            Vue d'ensemble
          </TabsTrigger>
          <TabsTrigger 
            value="orders" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <ShoppingBag className="h-4 w-4" />
            Commandes
          </TabsTrigger>
          <TabsTrigger 
            value="tracking" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Activity className="h-4 w-4" />
            Suivi Live
          </TabsTrigger>
          <TabsTrigger 
            value="medical" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Heart className="h-4 w-4" />
            Profil médical
          </TabsTrigger>
          <TabsTrigger 
            value="wallet" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Wallet className="h-4 w-4" />
            Portefeuille
          </TabsTrigger>
          <TabsTrigger 
            value="analytics" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <BarChart3 className="h-4 w-4" />
            Analytics
          </TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          {/* Real-time Notifications */}
          <div className="grid lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2">
              <NotificationCenter variant="panel" />
            </div>
            
            {/* Quick Actions */}
            <div className="space-y-4">
              <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('orders')}
                  >
                    <ShoppingBag className="h-4 w-4 mr-2" />
                    Voir mes commandes
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                    onClick={() => setActiveTab('medical')}
                  >
                    <Heart className="h-4 w-4 mr-2" />
                    Profil médical
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                    onClick={() => setActiveTab('wallet')}
                  >
                    <Wallet className="h-4 w-4 mr-2" />
                    Recharger portefeuille
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                    onClick={() => setShowSosModal(true)}
                  >
                    <AlertCircle className="h-4 w-4 mr-2" />
                    Demande d'urgence
                  </Button>
                </CardContent>
              </Card>
            </div>
          </div>

          {/* Recent Orders Preview */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <ShoppingBag className="h-5 w-5" />
                  Commandes récentes
                </CardTitle>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => setActiveTab('orders')}
                >
                  Voir tout
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {orders.length === 0 ? (
                <div className="text-center py-8">
                  <ShoppingBag 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</h3>
                  <p className="text-muted-foreground mb-4">
                    Commencez par votre première demande SOS
                  </p>
                  <Button onClick={() => setShowSosModal(true)}>
                    <Plus className="mr-2 h-4 w-4" />
                    Première demande
                  </Button>
                </div>
              ) : (
                <div className="space-y-3">
                  {orders.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">
                        <Pill 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.medicineName}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        {getStatusBadge(order.status!)}
                        <Button variant="ghost" size="sm">
                          <Eye className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Orders Tab */}
        <TabsContent value="orders" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <ShoppingBag className="h-5 w-5" />
                Toutes mes commandes
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <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">Chargement des commandes...</p>
                </div>
              ) : orders.length === 0 ? (
                <div className="text-center py-12">
                  <ShoppingBag 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</h3>
                  <p className="text-muted-foreground mb-4">
                    Vous n'avez pas encore passé de commandes SOS.
                  </p>
                  <Button onClick={() => setShowSosModal(true)}>
                    <Plus className="mr-2 h-4 w-4" />
                    Première demande SOS
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  {orders.map((order) => (
                    <div key={order.id} className="border rounded-lg p-4 hover:bg-gray-50 transition-colors" data-testid={`order-${order.id}`}>
                      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
                        {/* Order Info */}
                        <div className="flex-1 space-y-2">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <h3 className="font-medium">#{order.id.slice(0, 8)}</h3>
                              {getStatusBadge(order.status!)}
                            </div>
                            <div className="text-sm text-muted-foreground">
                              {order.createdAt ? new Date(order.createdAt).toLocaleDateString('fr-FR') : 'Date inconnue'}
                            </div>
                          </div>
                          
                          <div className="grid md:grid-cols-3 gap-4 text-sm">
                            <div className="flex items-center gap-2">
                              <Pill className="h-4 w-4 text-primary" />
                              <div>
                                <div className="font-medium">{order.medicineName}</div>
                                <div className="text-muted-foreground">Qté: {order.qty}</div>
                              </div>
                            </div>
                            
                            {order.pharmacy && (
                              <div className="flex items-center gap-2">
                                <MapPin className="h-4 w-4 text-primary" />
                                <div>
                                  <div className="font-medium">{order.pharmacy.name}</div>
                                  <div className="text-muted-foreground">{order.distanceKm} km</div>
                                </div>
                              </div>
                            )}
                            
                            <div className="flex items-center gap-2">
                              <div className="text-right">
                                <div className="font-bold text-green-600">
                                  {((order.medPriceTotal || 0) + (order.serviceFee || 0) + (order.deliveryFee || 0))} FCFA
                                </div>
                                <div className="text-xs text-muted-foreground">Total</div>
                              </div>
                            </div>
                          </div>
                        </div>

                        {/* Actions */}
                        <div className="flex items-center gap-2">
                          {order.status !== 'DELIVERED' && order.status !== 'CLOSED' && (
                            <Button variant="outline" size="sm" data-testid={`button-track-${order.id}`}>
                              <Eye className="h-4 w-4 mr-1" />
                              Suivre
                            </Button>
                          )}
                          
                          {(order.status === 'DELIVERED' || order.status === 'CLOSED') && (
                            <Button variant="outline" size="sm" data-testid={`button-receipt-${order.id}`}>
                              <Receipt className="h-4 w-4 mr-1" />
                              Reçu
                            </Button>
                          )}
                          
                          {order.courier && (
                            <Button variant="outline" size="sm" data-testid={`button-call-courier-${order.id}`}>
                              <Phone className="h-4 w-4 mr-1" />
                              Appeler
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Real-time Tracking Tab */}
        <TabsContent value="tracking" className="space-y-6">
          <div className="grid gap-6">
            {/* Active Order Tracking */}
            {orders.filter(order => order.status && !['DELIVERED', 'CANCELLED'].includes(order.status)).map((order) => (
              <OrderTracker
                key={order.id}
                orderId={order.id}
                initialOrder={order}
                userRole="client"
                onUpdateStatus={(status) => {
                  // Handle status update
                  console.log(`Order ${order.id} updated to ${status}`);
                }}
              />
            ))}
            
            {/* No Active Orders */}
            {orders.filter(order => order.status && !['DELIVERED', 'CANCELLED'].includes(order.status)).length === 0 && (
              <Card>
                <CardContent className="p-12 text-center">
                  <Activity className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-600 mb-2">
                    Aucune commande active
                  </h3>
                  <p className="text-muted-foreground mb-4">
                    Créez une nouvelle demande SOS pour voir le suivi en temps réel
                  </p>
                  <Button onClick={() => setShowSosModal(true)}>
                    <Plus className="mr-2 h-4 w-4" />
                    Nouvelle demande SOS
                  </Button>
                </CardContent>
              </Card>
            )}
          </div>
        </TabsContent>

        {/* Medical Profile Tab */}
        <TabsContent value="medical" className="space-y-6">
          <MedicalProfile userId={user.id} />
        </TabsContent>

        {/* Wallet Tab */}
        <TabsContent value="wallet" className="space-y-6">
          <WalletDashboard />
        </TabsContent>

        {/* Analytics Tab */}
        <TabsContent value="analytics" className="space-y-6">
          <ClientAnalytics userId={user.id} />
        </TabsContent>
      </Tabs>
    </div>
  );
}