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 { Button } from '@/components/ui/button';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  LineChart,
  Line,
  Area,
  AreaChart,
  PieChart,
  Pie,
  Cell,
  Tooltip
} from 'recharts';
import {
  DollarSign,
  TrendingUp,
  TrendingDown,
  Clock,
  Package,
  Star,
  Target,
  Award,
  Calendar,
  Fuel,
  Route,
  Activity
} from 'lucide-react';

interface CourierEarningsProps {
  courierId: string;
}

interface EarningsData {
  summary: {
    todayEarnings: number;
    weekEarnings: number;
    monthEarnings: number;
    totalEarnings: number;
    avgDeliveryEarning: number;
    completedDeliveries: number;
    rating: number;
    efficiency: number;
  };
  trends: {
    daily: Array<{ date: string; earnings: number; deliveries: number; hours: number }>;
    weekly: Array<{ week: string; earnings: number; efficiency: number }>;
    monthly: Array<{ month: string; earnings: number; growth: number }>;
  };
  breakdowns: {
    byTimeOfDay: Array<{ hour: string; earnings: number; count: number }>;
    byDistance: Array<{ range: string; earnings: number; count: number; color: string }>;
    byPriority: Array<{ priority: string; earnings: number; bonus: number; count: number }>;
  };
  bonuses: {
    speedBonus: number;
    qualityBonus: number;
    consistencyBonus: number;
    peakHourBonus: number;
    totalBonuses: number;
  };
  expenses: {
    fuel: number;
    maintenance: number;
    insurance: number;
    other: number;
    total: number;
  };
  goals: {
    dailyTarget: number;
    weeklyTarget: number;
    monthlyTarget: number;
    currentProgress: {
      daily: number;
      weekly: number;
      monthly: number;
    };
  };
}

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

export function CourierEarningsDashboard({ courierId }: CourierEarningsProps) {
  const { data: earnings, isLoading } = useQuery<EarningsData>({
    queryKey: ['/api/courier/earnings', courierId],
    initialData: {
      summary: {
        todayEarnings: 25000,
        weekEarnings: 165000,
        monthEarnings: 680000,
        totalEarnings: 2450000,
        avgDeliveryEarning: 1850,
        completedDeliveries: 342,
        rating: 4.8,
        efficiency: 92
      },
      trends: {
        daily: [
          { date: '01/12', earnings: 22000, deliveries: 12, hours: 8.5 },
          { date: '02/12', earnings: 28000, deliveries: 15, hours: 9.2 },
          { date: '03/12', earnings: 25000, deliveries: 14, hours: 8.8 },
          { date: '04/12', earnings: 31000, deliveries: 17, hours: 10.1 },
          { date: '05/12', earnings: 24000, deliveries: 13, hours: 8.3 },
          { date: '06/12', earnings: 35000, deliveries: 19, hours: 10.5 },
          { date: '07/12', earnings: 26000, deliveries: 14, hours: 9.0 },
        ],
        weekly: [
          { week: 'S48', earnings: 145000, efficiency: 89 },
          { week: 'S49', earnings: 158000, efficiency: 91 },
          { week: 'S50', earnings: 165000, efficiency: 92 },
          { week: 'S01', earnings: 172000, efficiency: 94 },
        ],
        monthly: [
          { month: 'Oct', earnings: 620000, growth: 8.5 },
          { month: 'Nov', earnings: 665000, growth: 7.2 },
          { month: 'Déc', earnings: 680000, growth: 2.3 },
        ]
      },
      breakdowns: {
        byTimeOfDay: [
          { hour: '06h', earnings: 3200, count: 2 },
          { hour: '08h', earnings: 8500, count: 5 },
          { hour: '10h', earnings: 12000, count: 7 },
          { hour: '12h', earnings: 15500, count: 8 },
          { hour: '14h', earnings: 14200, count: 8 },
          { hour: '16h', earnings: 13800, count: 7 },
          { hour: '18h', earnings: 16800, count: 9 },
          { hour: '20h', earnings: 11200, count: 6 },
        ],
        byDistance: [
          { range: '0-5km', earnings: 125000, count: 95, color: COLORS[0] },
          { range: '5-10km', earnings: 185000, count: 78, color: COLORS[1] },
          { range: '10-15km', earnings: 145000, count: 42, color: COLORS[2] },
          { range: '15km+', earnings: 95000, count: 28, color: COLORS[3] },
        ],
        byPriority: [
          { priority: 'Urgent', earnings: 285000, bonus: 45000, count: 89 },
          { priority: 'Normal', earnings: 320000, bonus: 25000, count: 185 },
          { priority: 'Différable', earnings: 75000, bonus: 5000, count: 68 },
        ]
      },
      bonuses: {
        speedBonus: 28000,
        qualityBonus: 35000,
        consistencyBonus: 15000,
        peakHourBonus: 22000,
        totalBonuses: 100000
      },
      expenses: {
        fuel: 85000,
        maintenance: 25000,
        insurance: 15000,
        other: 12000,
        total: 137000
      },
      goals: {
        dailyTarget: 30000,
        weeklyTarget: 200000,
        monthlyTarget: 800000,
        currentProgress: {
          daily: 25000,
          weekly: 165000,
          monthly: 680000
        }
      }
    }
  });

  if (isLoading || !earnings) {
    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">
      {/* Summary Cards */}
      <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">Gains aujourd'hui</p>
                <p className="text-2xl font-bold">
                  {(earnings.summary.todayEarnings / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-green-200 flex items-center mt-1">
                  <TrendingUp className="h-3 w-3 mr-1" />
                  +12% vs hier
                </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">Cette semaine</p>
                <p className="text-2xl font-bold">
                  {(earnings.summary.weekEarnings / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-blue-200 flex items-center mt-1">
                  <Package className="h-3 w-3 mr-1" />
                  78 livraisons
                </p>
              </div>
              <Calendar 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">Ce mois</p>
                <p className="text-2xl font-bold">
                  {(earnings.summary.monthEarnings / 1000).toFixed(0)}k F
                </p>
                <p className="text-xs text-purple-200 flex items-center mt-1">
                  <Target className="h-3 w-3 mr-1" />
                  85% objectif
                </p>
              </div>
              <TrendingUp 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">Note moyenne</p>
                <p className="text-2xl font-bold flex items-center">
                  {earnings.summary.rating}
                  <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" />
                  Top 5% livreurs
                </p>
              </div>
              <Activity className="h-8 w-8 text-orange-200" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Goals Progress */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Target className="h-5 w-5" />
            Progression des Objectifs
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-3 gap-6">
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>Objectif quotidien</span>
                <span className="font-medium">
                  {(earnings.goals.currentProgress.daily / 1000).toFixed(0)}k / {(earnings.goals.dailyTarget / 1000).toFixed(0)}k F
                </span>
              </div>
              <Progress 
                value={(earnings.goals.currentProgress.daily / earnings.goals.dailyTarget) * 100} 
                className="h-3"
              />
              <p className="text-xs text-muted-foreground">
                {((earnings.goals.currentProgress.daily / earnings.goals.dailyTarget) * 100).toFixed(1)}% atteint
              </p>
            </div>
            
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>Objectif hebdomadaire</span>
                <span className="font-medium">
                  {(earnings.goals.currentProgress.weekly / 1000).toFixed(0)}k / {(earnings.goals.weeklyTarget / 1000).toFixed(0)}k F
                </span>
              </div>
              <Progress 
                value={(earnings.goals.currentProgress.weekly / earnings.goals.weeklyTarget) * 100} 
                className="h-3"
              />
              <p className="text-xs text-muted-foreground">
                {((earnings.goals.currentProgress.weekly / earnings.goals.weeklyTarget) * 100).toFixed(1)}% atteint
              </p>
            </div>
            
            <div className="space-y-2">
              <div className="flex items-center justify-between text-sm">
                <span>Objectif mensuel</span>
                <span className="font-medium">
                  {(earnings.goals.currentProgress.monthly / 1000).toFixed(0)}k / {(earnings.goals.monthlyTarget / 1000).toFixed(0)}k F
                </span>
              </div>
              <Progress 
                value={(earnings.goals.currentProgress.monthly / earnings.goals.monthlyTarget) * 100} 
                className="h-3"
              />
              <p className="text-xs text-muted-foreground">
                {((earnings.goals.currentProgress.monthly / earnings.goals.monthlyTarget) * 100).toFixed(1)}% atteint
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Earnings Trend */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Évolution des Gains (7 derniers jours)
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="h-80">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={earnings.trends.daily}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip 
                  formatter={(value, name) => [
                    name === 'earnings' ? `${(value as number).toLocaleString()} F` : `${value}${name === 'hours' ? 'h' : ''}`,
                    name === 'earnings' ? 'Gains' : name === 'deliveries' ? 'Livraisons' : 'Heures'
                  ]}
                />
                <Area
                  yAxisId="left"
                  type="monotone"
                  dataKey="earnings"
                  stroke="#8884d8"
                  fill="#8884d8"
                  fillOpacity={0.3}
                  name="earnings"
                />
                <Line
                  yAxisId="right"
                  type="monotone"
                  dataKey="deliveries"
                  stroke="#82ca9d"
                  strokeWidth={2}
                  name="deliveries"
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      <div className="grid md:grid-cols-2 gap-6">
        {/* Earnings by Time of Day */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="h-5 w-5" />
              Gains par Heure
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={earnings.breakdowns.byTimeOfDay}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="hour" />
                  <YAxis />
                  <Tooltip formatter={(value) => [`${(value as number).toLocaleString()} F`, 'Gains']} />
                  <Bar dataKey="earnings" fill="#8884d8" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Earnings by Distance */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Route className="h-5 w-5" />
              Gains par Distance
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={earnings.breakdowns.byDistance}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ range, earnings }) => `${range}: ${(earnings/1000).toFixed(0)}k`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="earnings"
                  >
                    {earnings.breakdowns.byDistance.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value) => [`${(value as number).toLocaleString()} F`, 'Gains']} />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Bonuses and Expenses */}
      <div className="grid md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Award className="h-5 w-5" />
              Bonus de Performance
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm">Bonus rapidité</span>
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">
                    {(earnings.bonuses.speedBonus / 1000).toFixed(0)}k F
                  </Badge>
                  <Progress value={85} className="w-16" />
                </div>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Bonus qualité</span>
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">
                    {(earnings.bonuses.qualityBonus / 1000).toFixed(0)}k F
                  </Badge>
                  <Progress value={92} className="w-16" />
                </div>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Bonus régularité</span>
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">
                    {(earnings.bonuses.consistencyBonus / 1000).toFixed(0)}k F
                  </Badge>
                  <Progress value={78} className="w-16" />
                </div>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Bonus heures de pointe</span>
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">
                    {(earnings.bonuses.peakHourBonus / 1000).toFixed(0)}k F
                  </Badge>
                  <Progress value={88} className="w-16" />
                </div>
              </div>
              
              <div className="border-t pt-3 mt-3">
                <div className="flex items-center justify-between font-medium">
                  <span>Total bonus</span>
                  <Badge className="bg-green-100 text-green-800">
                    {(earnings.bonuses.totalBonuses / 1000).toFixed(0)}k F
                  </Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Fuel className="h-5 w-5" />
              Frais et Dépenses
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm">Carburant</span>
                <Badge variant="outline" className="text-red-600">
                  -{(earnings.expenses.fuel / 1000).toFixed(0)}k F
                </Badge>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Maintenance</span>
                <Badge variant="outline" className="text-red-600">
                  -{(earnings.expenses.maintenance / 1000).toFixed(0)}k F
                </Badge>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Assurance</span>
                <Badge variant="outline" className="text-red-600">
                  -{(earnings.expenses.insurance / 1000).toFixed(0)}k F
                </Badge>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm">Autres frais</span>
                <Badge variant="outline" className="text-red-600">
                  -{(earnings.expenses.other / 1000).toFixed(0)}k F
                </Badge>
              </div>
              
              <div className="border-t pt-3 mt-3">
                <div className="flex items-center justify-between font-medium">
                  <span>Total dépenses</span>
                  <Badge variant="outline" className="text-red-600">
                    -{(earnings.expenses.total / 1000).toFixed(0)}k F
                  </Badge>
                </div>
              </div>
              
              <div className="border-t pt-3 mt-3 bg-green-50 -mx-3 -mb-3 p-3 rounded-b-lg">
                <div className="flex items-center justify-between font-medium">
                  <span>Gain net ce mois</span>
                  <Badge className="bg-green-600 text-white">
                    {((earnings.summary.monthEarnings + earnings.bonuses.totalBonuses - earnings.expenses.total) / 1000).toFixed(0)}k F
                  </Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Performance Metrics */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            Métriques de Performance
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-4 gap-6">
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-green-600 mb-2">
                {(earnings.summary.avgDeliveryEarning / 1000).toFixed(1)}k F
              </div>
              <p className="text-sm text-muted-foreground mb-2">Gain moyen/livraison</p>
              <Progress value={75} className="mt-2" />
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-blue-600 mb-2">
                {earnings.summary.completedDeliveries}
              </div>
              <p className="text-sm text-muted-foreground mb-2">Livraisons complétées</p>
              <Progress value={90} className="mt-2" />
            </div>
            
            <div className="text-center p-4 border rounded-lg">
              <div className="text-3xl font-bold text-purple-600 mb-2">
                {earnings.summary.efficiency}%
              </div>
              <p className="text-sm text-muted-foreground mb-2">Efficacité globale</p>
              <Progress value={earnings.summary.efficiency} className="mt-2" />
            </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">
                {earnings.summary.rating}
                <Star className="h-6 w-6 ml-1 fill-current" />
              </div>
              <p className="text-sm text-muted-foreground mb-2">Note satisfaction</p>
              <Progress value={(earnings.summary.rating / 5) * 100} className="mt-2" />
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}