import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  Area,
  AreaChart,
  Tooltip,
  Legend
} from 'recharts';
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  Package,
  Users,
  Clock,
  Target,
  Award,
  Activity,
  ShoppingBag,
  Star,
  AlertTriangle
} from 'lucide-react';

interface PharmacyAnalyticsProps {
  pharmacyId: string;
}

interface AnalyticsData {
  revenue: {
    today: number;
    thisWeek: number;
    thisMonth: number;
    trend: Array<{ date: string; revenue: number; orders: number }>;
  };
  orders: {
    total: number;
    pending: number;
    completed: number;
    cancelled: number;
    avgOrderValue: number;
    peakHours: Array<{ hour: string; orders: number }>;
  };
  inventory: {
    totalValue: number;
    lowStockItems: number;
    fastMovingItems: Array<{ name: string; turnover: number; revenue: number }>;
    categoryPerformance: Array<{ category: string; sales: number; color: string }>;
  };
  customers: {
    totalCustomers: number;
    newCustomers: number;
    returningRate: number;
    topCustomers: Array<{ name: string; orders: number; totalSpent: number }>;
    satisfaction: number;
  };
  performance: {
    deliveryTime: number;
    fulfillmentRate: number;
    stockAccuracy: number;
    customerRating: number;
    monthlyGrowth: number;
  };
}

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8', '#82CA9D'];

export function PharmacyAnalytics({ pharmacyId }: PharmacyAnalyticsProps) {
  const { data: analytics, isLoading } = useQuery<AnalyticsData>({
    queryKey: ['/api/pharmacy/analytics', pharmacyId],
    initialData: {
      revenue: {
        today: 125000,
        thisWeek: 850000,
        thisMonth: 3200000,
        trend: [
          { date: '01/12', revenue: 95000, orders: 12 },
          { date: '02/12', revenue: 110000, orders: 15 },
          { date: '03/12', revenue: 125000, orders: 18 },
          { date: '04/12', revenue: 140000, orders: 20 },
          { date: '05/12', revenue: 105000, orders: 14 },
          { date: '06/12', revenue: 160000, orders: 22 },
          { date: '07/12', revenue: 145000, orders: 19 },
        ]
      },
      orders: {
        total: 1250,
        pending: 8,
        completed: 1200,
        cancelled: 42,
        avgOrderValue: 8500,
        peakHours: [
          { hour: '08h', orders: 15 },
          { hour: '10h', orders: 28 },
          { hour: '12h', orders: 35 },
          { hour: '14h', orders: 42 },
          { hour: '16h', orders: 38 },
          { hour: '18h', orders: 45 },
          { hour: '20h', orders: 32 },
          { hour: '22h', orders: 18 },
        ]
      },
      inventory: {
        totalValue: 5800000,
        lowStockItems: 12,
        fastMovingItems: [
          { name: 'Paracétamol', turnover: 15.2, revenue: 285000 },
          { name: 'Amoxicilline', turnover: 12.8, revenue: 320000 },
          { name: 'Ibuprofène', turnover: 11.5, revenue: 245000 },
          { name: 'Aspirine', turnover: 9.3, revenue: 180000 },
          { name: 'Oméprazole', turnover: 8.7, revenue: 195000 },
        ],
        categoryPerformance: [
          { category: 'Antalgiques', sales: 450000, color: COLORS[0] },
          { category: 'Antibiotiques', sales: 380000, color: COLORS[1] },
          { category: 'Anti-inflammatoires', sales: 320000, color: COLORS[2] },
          { category: 'Cardiovasculaires', sales: 280000, color: COLORS[3] },
          { category: 'Respiratoires', sales: 240000, color: COLORS[4] },
          { category: 'Autres', sales: 200000, color: COLORS[5] },
        ]
      },
      customers: {
        totalCustomers: 2450,
        newCustomers: 145,
        returningRate: 68,
        topCustomers: [
          { name: 'Dr. Kouamé Jean', orders: 45, totalSpent: 385000 },
          { name: 'Mme Assi Marie', orders: 38, totalSpent: 320000 },
          { name: 'M. Yao Koffi', orders: 32, totalSpent: 285000 },
          { name: 'Dr. Bamba Paul', orders: 28, totalSpent: 245000 },
          { name: 'Mme Diabaté Awa', orders: 25, totalSpent: 220000 },
        ],
        satisfaction: 4.6
      },
      performance: {
        deliveryTime: 28,
        fulfillmentRate: 96,
        stockAccuracy: 98,
        customerRating: 4.6,
        monthlyGrowth: 12.5
      }
    }
  });

  if (isLoading || !analytics) {
    return (
      <div className="grid gap-6">
        {Array.from({ length: 6 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="p-6">
              <div className="animate-pulse space-y-4">
                <div className="h-4 bg-gray-200 rounded w-1/3"></div>
                <div className="h-32 bg-gray-200 rounded"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 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-green-600 to-green-700 text-white">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-green-100 text-sm">Chiffre d'affaires</p>
                <p className="text-2xl font-bold">
                  {(analytics.revenue.thisMonth / 1000000).toFixed(1)}M F
                </p>
                <p className="text-xs text-green-200 flex items-center mt-1">
                  <TrendingUp className="h-3 w-3 mr-1" />
                  +{analytics.performance.monthlyGrowth}% ce mois
                </p>
              </div>
              <DollarSign className="h-8 w-8 text-green-200" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-br from-blue-600 to-blue-700 text-white">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-blue-100 text-sm">Commandes</p>
                <p className="text-2xl font-bold">{analytics.orders.total}</p>
                <p className="text-xs text-blue-200 flex items-center mt-1">
                  <Package className="h-3 w-3 mr-1" />
                  {analytics.performance.fulfillmentRate}% complétées
                </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">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-purple-100 text-sm">Clients actifs</p>
                <p className="text-2xl font-bold">{analytics.customers.totalCustomers}</p>
                <p className="text-xs text-purple-200 flex items-center mt-1">
                  <Users className="h-3 w-3 mr-1" />
                  +{analytics.customers.newCustomers} nouveaux
                </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">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-orange-100 text-sm">Satisfaction</p>
                <p className="text-2xl font-bold flex items-center">
                  {analytics.customers.satisfaction}
                  <Star className="h-5 w-5 ml-1 fill-current" />
                </p>
                <p className="text-xs text-orange-200 flex items-center mt-1">
                  <Award className="h-3 w-3 mr-1" />
                  Excellent service
                </p>
              </div>
              <Activity className="h-8 w-8 text-orange-200" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Revenue Trend */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Évolution du Chiffre d'Affaires
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={analytics.revenue.trend}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip 
                  formatter={(value, name) => [
                    name === 'revenue' ? `${(value as number).toLocaleString()} F` : value,
                    name === 'revenue' ? 'Chiffre d\'affaires' : 'Commandes'
                  ]}
                />
                <Area
                  yAxisId="left"
                  type="monotone"
                  dataKey="revenue"
                  stroke="#8884d8"
                  fill="#8884d8"
                  fillOpacity={0.3}
                  name="revenue"
                />
                <Line
                  yAxisId="right"
                  type="monotone"
                  dataKey="orders"
                  stroke="#82ca9d"
                  strokeWidth={2}
                  name="orders"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Peak Hours */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="h-5 w-5" />
              Heures de Pointe
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={analytics.orders.peakHours}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="hour" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="orders" fill="#8884d8" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Category Performance */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Target className="h-5 w-5" />
              Performance par Catégorie
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={analytics.inventory.categoryPerformance}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ category, sales }) => `${category}: ${(sales/1000).toFixed(0)}k`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="sales"
                  >
                    {analytics.inventory.categoryPerformance.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value) => [`${(value as number).toLocaleString()} F`, 'Ventes']} />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Fast Moving Items */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Médicaments à Rotation Rapide
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {analytics.inventory.fastMovingItems.map((item, index) => (
              <div key={item.name} className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <span className="text-sm font-medium text-primary">{index + 1}</span>
                  </div>
                  <div>
                    <p className="font-medium">{item.name}</p>
                    <p className="text-sm text-muted-foreground">
                      Rotation: {item.turnover}x/mois
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <p className="font-medium text-green-600">
                      {(item.revenue / 1000).toFixed(0)}k F
                    </p>
                    <p className="text-sm text-muted-foreground">Revenus</p>
                  </div>
                  <Progress 
                    value={(item.turnover / analytics.inventory.fastMovingItems[0].turnover) * 100} 
                    className="w-20"
                  />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Performance Metrics */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            Indicateurs de Performance
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-blue-600 mb-2">
                {analytics.performance.deliveryTime}min
              </div>
              <p className="text-sm text-muted-foreground mb-2">Temps de livraison moyen</p>
              <Progress value={85} className="mt-2" />
              <p className="text-xs text-green-600 mt-1">-5min ce mois</p>
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-green-600 mb-2">
                {analytics.performance.fulfillmentRate}%
              </div>
              <p className="text-sm text-muted-foreground mb-2">Taux de satisfaction</p>
              <Progress value={analytics.performance.fulfillmentRate} className="mt-2" />
              <p className="text-xs text-green-600 mt-1">Excellent</p>
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-purple-600 mb-2">
                {analytics.performance.stockAccuracy}%
              </div>
              <p className="text-sm text-muted-foreground mb-2">Précision du stock</p>
              <Progress value={analytics.performance.stockAccuracy} className="mt-2" />
              <p className="text-xs text-green-600 mt-1">Très précis</p>
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-orange-600 mb-2 flex items-center justify-center">
                {analytics.performance.customerRating}
                <Star className="h-6 w-6 ml-1 fill-current" />
              </div>
              <p className="text-sm text-muted-foreground mb-2">Note clients</p>
              <Progress value={(analytics.performance.customerRating / 5) * 100} className="mt-2" />
              <p className="text-xs text-green-600 mt-1">Très satisfait</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Top Customers */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            Meilleurs Clients
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {analytics.customers.topCustomers.map((customer, index) => (
              <div key={customer.name} className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <span className="text-sm font-medium text-primary">{index + 1}</span>
                  </div>
                  <div>
                    <p className="font-medium">{customer.name}</p>
                    <p className="text-sm text-muted-foreground">
                      {customer.orders} commandes
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Badge variant="secondary">
                    {(customer.totalSpent / 1000).toFixed(0)}k F
                  </Badge>
                  <div className="flex items-center">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star
                        key={i}
                        className={`h-4 w-4 ${
                          i < 4 ? 'text-yellow-400 fill-current' : 'text-gray-300'
                        }`}
                      />
                    ))}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Alerts and Recommendations */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5 text-yellow-600" />
            Alertes et Recommandations
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            <div className="p-3 border rounded-lg bg-yellow-50 border-yellow-200">
              <div className="flex items-center gap-2">
                <AlertTriangle className="h-4 w-4 text-yellow-600" />
                <p className="font-medium text-yellow-800">
                  {analytics.inventory.lowStockItems} médicaments en stock faible
                </p>
              </div>
              <p className="text-sm text-yellow-700 mt-1">
                Réapprovisionnez rapidement pour éviter les ruptures
              </p>
            </div>
            
            <div className="p-3 border rounded-lg bg-green-50 border-green-200">
              <div className="flex items-center gap-2">
                <TrendingUp className="h-4 w-4 text-green-600" />
                <p className="font-medium text-green-800">
                  Croissance de {analytics.performance.monthlyGrowth}% ce mois
                </p>
              </div>
              <p className="text-sm text-green-700 mt-1">
                Excellente performance, continuez sur cette lancée
              </p>
            </div>
            
            <div className="p-3 border rounded-lg bg-blue-50 border-blue-200">
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-blue-600" />
                <p className="font-medium text-blue-800">
                  Pic d'activité entre 14h et 18h
                </p>
              </div>
              <p className="text-sm text-blue-700 mt-1">
                Assurez-vous d'avoir suffisamment de personnel pendant ces heures
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}