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 { PharmacyStockManagement } from '@/components/pharmacy-stock-management';
import { PharmacyInventoryManagement } from '@/components/pharmacy-inventory-management';
import { PharmacyAnalytics } from '@/components/pharmacy-analytics';
import { ORDER_STATUSES } from '@/lib/constants';
import { OrderWithDetails } from '@shared/schema';
import { useAuth } from '@/contexts/AuthContext';
import {
  Store,
  AlertTriangle,
  Clock,
  DollarSign,
  Package,
  Check,
  X,
  Eye,
  History,
  Wallet,
  TrendingUp,
  Users,
  Phone,
  MapPin,
  Pill,
  BarChart3,
  PackageSearch,
  ShoppingBag,
  Bell
} from 'lucide-react';

export function EnhancedPharmacyDashboard() {
  const { user, isAuthenticated } = useAuth();
  const [activeTab, setActiveTab] = useState('overview');
  const [processingOrders, setProcessingOrders] = useState<Set<string>>(new Set());

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

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

  const pharmacyData = (user as any).pharmacy || {};
  
  // Fetch pending orders for this pharmacy
  const { data: pendingOrders = [], isLoading } = useQuery<OrderWithDetails[]>({
    queryKey: ['/api/orders', { userId: user.id, role: 'pharmacy', status: 'CREATED,PHARMACY_CONFIRMED' }],
    enabled: isAuthenticated && !!user?.id,
  });

  // Fetch pharmacy stats
  const { data: stats } = useQuery({
    queryKey: ['/api/pharmacy/stats', user.id],
    initialData: {
      today_orders: 18,
      today_revenue: 145000,
      pending_count: pendingOrders.length,
      weekly_revenue: 850000,
      monthly_revenue: 3200000,
      total_customers: 1250,
      verified_status: pharmacyData.verified || false,
      rating: 4.7,
      completion_rate: 96,
      avg_preparation_time: 12
    }
  });

  return (
    <div className="container mx-auto p-4 space-y-6" data-testid="enhanced-pharmacy-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">
            <Store className="h-8 w-8" />
            Dashboard Pharmacie Pro
          </h1>
          <p className="text-muted-foreground">
            <span className="font-medium">{pharmacyData.name || user.name}</span> • 
            Gestion professionnelle avancée
          </p>
        </div>
        
        {!stats.verified_status && (
          <Alert className="max-w-sm">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription className="text-sm">
              <strong>Vérification requise</strong> - Contactez l'administration pour valider votre pharmacie.
            </AlertDescription>
          </Alert>
        )}
      </div>

      {/* Key Performance Indicators */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="bg-gradient-to-br from-emerald-600 to-emerald-700 text-white hover:shadow-lg transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-emerald-100 text-sm">Revenus aujourd'hui</p>
                <p className="text-2xl font-bold">
                  {(stats.today_revenue / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-emerald-200 mt-1">
                  +15% vs hier
                </p>
              </div>
              <DollarSign className="h-8 w-8 text-emerald-200" />
            </div>
          </CardContent>
        </Card>

        <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 aujourd'hui</p>
                <p className="text-2xl font-bold">{stats.today_orders}</p>
                <p className="text-xs text-blue-200 mt-1">
                  {stats.pending_count} en attente
                </p>
              </div>
              <ShoppingBag className="h-8 w-8 text-blue-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">Clients servis</p>
                <p className="text-2xl font-bold">{stats.total_customers}</p>
                <p className="text-xs text-purple-200 mt-1">
                  Fidélité: 68%
                </p>
              </div>
              <Users 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">Note satisfaction</p>
                <p className="text-2xl font-bold">{stats.rating}/5</p>
                <p className="text-xs text-orange-200 mt-1">
                  {stats.completion_rate}% réussite
                </p>
              </div>
              <TrendingUp className="h-8 w-8 text-orange-200" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Priority Alerts */}
      {stats.pending_count > 5 && (
        <Alert className="border-red-200 bg-gradient-to-r from-red-50 to-pink-50">
          <Bell className="h-4 w-4 text-red-600" />
          <AlertDescription>
            <strong>Attention !</strong> Vous avez {stats.pending_count} commandes en attente. 
            Traitez-les rapidement pour maintenir votre niveau de service.
          </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"
          >
            <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
            {stats.pending_count > 0 && (
              <Badge variant="destructive" className="ml-1 px-1.5 py-0.5 text-xs">
                {stats.pending_count}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger 
            value="inventory" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <PackageSearch className="h-4 w-4" />
            Inventaire
          </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>
          <TabsTrigger 
            value="stock" 
            className="flex items-center gap-2 data-[state=active]:bg-white data-[state=active]:shadow-sm"
          >
            <Package className="h-4 w-4" />
            Stock
          </TabsTrigger>
        </TabsList>

        {/* Overview Tab */}
        <TabsContent value="overview" className="space-y-6">
          {/* Quick Stats */}
          <div className="grid md:grid-cols-3 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Revenus mensuels</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-green-600 mb-2">
                  {(stats.monthly_revenue / 1000000).toFixed(1)}M F
                </div>
                <p className="text-sm text-muted-foreground">
                  Cette semaine: {(stats.weekly_revenue / 1000).toFixed(0)}k F
                </p>
                <div className="mt-3">
                  <div className="flex items-center text-sm text-green-600">
                    <TrendingUp className="h-4 w-4 mr-1" />
                    +12% par rapport au mois dernier
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Performance</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Temps de préparation</span>
                    <Badge variant="secondary">{stats.avg_preparation_time}min</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Taux de réussite</span>
                    <Badge variant="secondary">{stats.completion_rate}%</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm">Note clients</span>
                    <div className="flex items-center">
                      <span className="font-medium mr-1">{stats.rating}</span>
                      <div className="flex">
                        {[1,2,3,4,5].map(star => (
                          <span key={star} className={star <= stats.rating ? "text-yellow-400" : "text-gray-300"}>★</span>
                        ))}
                      </div>
                    </div>
                  </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('orders')}
                >
                  <ShoppingBag className="h-4 w-4 mr-2" />
                  Traiter les commandes ({stats.pending_count})
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('inventory')}
                >
                  <PackageSearch className="h-4 w-4 mr-2" />
                  Gérer l'inventaire
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('analytics')}
                >
                  <BarChart3 className="h-4 w-4 mr-2" />
                  Voir les analytics
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full justify-start"
                  onClick={() => setActiveTab('stock')}
                >
                  <Package className="h-4 w-4 mr-2" />
                  Gérer le stock
                </Button>
              </CardContent>
            </Card>
          </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 toutes
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {pendingOrders.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 en attente</h3>
                  <p className="text-muted-foreground">
                    Excellente gestion ! Toutes les commandes ont été traitées.
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {pendingOrders.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">
                        <Badge variant="secondary">
                          {order.qty} unités
                        </Badge>
                        <Badge className="bg-yellow-100 text-yellow-800">
                          En attente
                        </Badge>
                        <Button variant="ghost" size="sm">
                          <Eye className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Orders Tab - Use existing component logic */}
        <TabsContent value="orders" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <ShoppingBag className="h-5 w-5" />
                Gestion des 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>
              ) : pendingOrders.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 en attente</h3>
                  <p className="text-muted-foreground">
                    Parfait ! Toutes les commandes ont été traitées.
                  </p>
                </div>
              ) : (
                <div className="space-y-4">
                  {pendingOrders.map((order) => (
                    <div key={order.id} className="border rounded-lg p-4 hover:bg-gray-50 transition-colors">
                      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
                        <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>
                              <Badge className="bg-yellow-100 text-yellow-800">En attente</Badge>
                            </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>
                            
                            <div className="flex items-center gap-2">
                              <MapPin className="h-4 w-4 text-primary" />
                              <div>
                                <div className="font-medium">{order.clientName}</div>
                                <div className="text-muted-foreground">{order.clientAddress}</div>
                              </div>
                            </div>
                            
                            <div className="flex items-center gap-2">
                              <DollarSign className="h-4 w-4 text-primary" />
                              <div>
                                <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>

                        <div className="flex items-center gap-2">
                          <Button 
                            variant="outline" 
                            size="sm"
                            className="text-red-600 hover:text-red-700"
                          >
                            <X className="h-4 w-4 mr-1" />
                            Refuser
                          </Button>
                          <Button size="sm">
                            <Check className="h-4 w-4 mr-1" />
                            Accepter
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Inventory Tab */}
        <TabsContent value="inventory" className="space-y-6">
          <PharmacyInventoryManagement pharmacyId={user.id} />
        </TabsContent>

        {/* Analytics Tab */}
        <TabsContent value="analytics" className="space-y-6">
          <PharmacyAnalytics pharmacyId={user.id} />
        </TabsContent>

        {/* Stock Tab */}
        <TabsContent value="stock" className="space-y-6">
          <PharmacyStockManagement />
        </TabsContent>
      </Tabs>
    </div>
  );
}