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
} from 'recharts';
import {
  TrendingUp,
  TrendingDown,
  Clock,
  DollarSign,
  Package,
  MapPin,
  Calendar,
  Target,
  Award,
  Activity
} from 'lucide-react';

interface ClientAnalyticsProps {
  userId: string;
}

interface AnalyticsData {
  orderStats: {
    totalOrders: number;
    completedOrders: number;
    avgDeliveryTime: number;
    totalSpent: number;
    monthlyTrend: Array<{ month: string; orders: number; spent: number }>;
  };
  medicineStats: {
    mostOrdered: Array<{ name: string; count: number; category: string }>;
    categoryBreakdown: Array<{ category: string; count: number; color: string }>;
  };
  timeStats: {
    averageOrderTime: string;
    preferredTimeSlots: Array<{ time: string; percentage: number }>;
    weekdayDistribution: Array<{ day: string; orders: number }>;
  };
  healthMetrics: {
    medicineAdherence: number;
    emergencyCallsReduced: number;
    healthScore: number;
  };
}

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

export function ClientAnalytics({ userId }: ClientAnalyticsProps) {
  const { data: analytics, isLoading } = useQuery<AnalyticsData>({
    queryKey: ['/api/client/analytics', userId],
    initialData: {
      orderStats: {
        totalOrders: 24,
        completedOrders: 22,
        avgDeliveryTime: 28,
        totalSpent: 285000,
        monthlyTrend: [
          { month: 'Jan', orders: 2, spent: 25000 },
          { month: 'Fév', orders: 4, spent: 35000 },
          { month: 'Mar', orders: 3, spent: 28000 },
          { month: 'Avr', orders: 5, spent: 42000 },
          { month: 'Mai', orders: 6, spent: 52000 },
          { month: 'Juin', orders: 4, spent: 38000 },
        ]
      },
      medicineStats: {
        mostOrdered: [
          { name: 'Paracétamol', count: 8, category: 'Antalgiques' },
          { name: 'Amoxicilline', count: 6, category: 'Antibiotiques' },
          { name: 'Ibuprofène', count: 5, category: 'Anti-inflammatoires' },
          { name: 'Oméprazole', count: 4, category: 'Gastro' },
          { name: 'Cetirizine', count: 3, category: 'Antihistaminiques' },
        ],
        categoryBreakdown: [
          { category: 'Antalgiques', count: 12, color: COLORS[0] },
          { category: 'Antibiotiques', count: 8, color: COLORS[1] },
          { category: 'Anti-inflammatoires', count: 6, color: COLORS[2] },
          { category: 'Gastro', count: 4, color: COLORS[3] },
          { category: 'Autres', count: 6, color: COLORS[4] },
        ]
      },
      timeStats: {
        averageOrderTime: '21:30',
        preferredTimeSlots: [
          { time: '06:00-12:00', percentage: 15 },
          { time: '12:00-18:00', percentage: 35 },
          { time: '18:00-24:00', percentage: 50 },
        ],
        weekdayDistribution: [
          { day: 'Lun', orders: 4 },
          { day: 'Mar', orders: 3 },
          { day: 'Mer', orders: 5 },
          { day: 'Jeu', orders: 2 },
          { day: 'Ven', orders: 6 },
          { day: 'Sam', orders: 3 },
          { day: 'Dim', orders: 1 },
        ]
      },
      healthMetrics: {
        medicineAdherence: 92,
        emergencyCallsReduced: 65,
        healthScore: 85
      }
    }
  });

  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">
      {/* Overview Stats */}
      <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 justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Commandes totales</p>
                <p className="text-2xl font-bold text-primary">{analytics.orderStats.totalOrders}</p>
                <p className="text-xs text-green-600 flex items-center mt-1">
                  <TrendingUp className="h-3 w-3 mr-1" />
                  +15% ce mois
                </p>
              </div>
              <Package className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Temps moyen</p>
                <p className="text-2xl font-bold text-primary">{analytics.orderStats.avgDeliveryTime}min</p>
                <p className="text-xs text-green-600 flex items-center mt-1">
                  <TrendingDown className="h-3 w-3 mr-1" />
                  -8% ce mois
                </p>
              </div>
              <Clock className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Montant dépensé</p>
                <p className="text-2xl font-bold text-primary">
                  {(analytics.orderStats.totalSpent / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-blue-600 flex items-center mt-1">
                  <DollarSign className="h-3 w-3 mr-1" />
                  Économisé 15%
                </p>
              </div>
              <DollarSign className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Score Santé</p>
                <p className="text-2xl font-bold text-primary">{analytics.healthMetrics.healthScore}</p>
                <p className="text-xs text-green-600 flex items-center mt-1">
                  <Award className="h-3 w-3 mr-1" />
                  Excellent
                </p>
              </div>
              <Activity className="h-8 w-8 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Monthly Trend Chart */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Évolution Mensuelle
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={analytics.orderStats.monthlyTrend}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Area
                  yAxisId="left"
                  type="monotone"
                  dataKey="orders"
                  stroke="#8884d8"
                  fill="#8884d8"
                  fillOpacity={0.3}
                  name="Commandes"
                />
                <Line
                  yAxisId="right"
                  type="monotone"
                  dataKey="spent"
                  stroke="#82ca9d"
                  strokeWidth={2}
                  name="Dépenses (F CFA)"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Medicine Categories Pie Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Target className="h-5 w-5" />
              Catégories de Médicaments
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={analytics.medicineStats.categoryBreakdown}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ category, percentage }) => `${category}: ${percentage}%`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="count"
                  >
                    {analytics.medicineStats.categoryBreakdown.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                </PieChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Weekly Distribution */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5" />
              Distribution Hebdomadaire
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={analytics.timeStats.weekdayDistribution}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="day" />
                  <YAxis />
                  <Bar dataKey="orders" fill="#8884d8" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Most Ordered Medicines */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Médicaments Les Plus Commandés
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {analytics.medicineStats.mostOrdered.map((medicine, index) => (
              <div key={medicine.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">{medicine.name}</p>
                    <p className="text-sm text-muted-foreground">{medicine.category}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Badge variant="secondary">{medicine.count} commandes</Badge>
                  <Progress 
                    value={(medicine.count / analytics.medicineStats.mostOrdered[0].count) * 100} 
                    className="w-20"
                  />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Health Metrics */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            Indicateurs de Santé
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-3 gap-6">
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-green-600 mb-2">
                {analytics.healthMetrics.medicineAdherence}%
              </div>
              <p className="text-sm text-muted-foreground">Observance médicamenteuse</p>
              <Progress value={analytics.healthMetrics.medicineAdherence} className="mt-2" />
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-blue-600 mb-2">
                -{analytics.healthMetrics.emergencyCallsReduced}%
              </div>
              <p className="text-sm text-muted-foreground">Appels d'urgence réduits</p>
              <Progress value={analytics.healthMetrics.emergencyCallsReduced} className="mt-2" />
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-purple-600 mb-2">
                {analytics.healthMetrics.healthScore}
              </div>
              <p className="text-sm text-muted-foreground">Score de santé global</p>
              <Progress value={analytics.healthMetrics.healthScore} className="mt-2" />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Time Preferences */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Clock className="h-5 w-5" />
            Créneaux Préférés
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {analytics.timeStats.preferredTimeSlots.map((slot) => (
              <div key={slot.time} className="flex items-center justify-between">
                <span className="font-medium">{slot.time}</span>
                <div className="flex items-center gap-3">
                  <span className="text-sm text-muted-foreground">{slot.percentage}%</span>
                  <Progress value={slot.percentage} className="w-32" />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}