
'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Trophy,
  Medal,
  Award,
  Star,
  TrendingUp,
  DollarSign,
  Target,
  CheckCircle2,
  Clock,
  Shield,
  Zap,
  Users,
} from 'lucide-react';

interface LeaderboardEntry {
  rank: number;
  contractorId: string;
  contractorName: string;
  companyName?: string;
  isVerified: boolean;
  services: string[];
  leadsAssigned: number;
  quotesSubmitted: number;
  contractsWon: number;
  revenue: number;
  averageRating: number;
  completionRate: number;
  customerSatisfaction: number;
  reviewCount: number;
  badges: any[];
  averageResponseTime: number | null;
  conversionRate: string;
}

interface LeaderboardData {
  leaderboard: LeaderboardEntry[];
  period: string;
  metric: string;
  stats: {
    totalContractors: number;
    totalRevenue: number;
    averageRating: string;
  };
}

const BADGE_ICONS: Record<string, any> = {
  VERIFIED_CONTRACTOR: Shield,
  TOP_RATED: Star,
  QUICK_RESPONDER: Zap,
  LICENSED_PROFESSIONAL: Award,
  INSURED: Shield,
  QUALITY_GUARANTEE: CheckCircle2,
};

const BADGE_COLORS: Record<string, string> = {
  VERIFIED_CONTRACTOR: 'bg-blue-500',
  TOP_RATED: 'bg-amber-500',
  QUICK_RESPONDER: 'bg-green-500',
  LICENSED_PROFESSIONAL: 'bg-purple-500',
  INSURED: 'bg-cyan-500',
  QUALITY_GUARANTEE: 'bg-emerald-500',
};

export default function ContractorLeaderboard() {
  const [data, setData] = useState<LeaderboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [metric, setMetric] = useState('revenue');
  const [period, setPeriod] = useState(() => {
    const date = new Date();
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
  });

  useEffect(() => {
    fetchLeaderboard();
  }, [metric, period]);

  const fetchLeaderboard = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `/api/contractors/leaderboard?metric=${metric}&period=${period}&limit=20`
      );
      if (response.ok) {
        const result = await response.json();
        setData(result);
      }
    } catch (error) {
      console.error('Error fetching leaderboard:', error);
    } finally {
      setLoading(false);
    }
  };

  const getRankIcon = (rank: number) => {
    if (rank === 1) return <Trophy className="w-6 h-6 text-amber-500" />;
    if (rank === 2) return <Medal className="w-6 h-6 text-gray-400" />;
    if (rank === 3) return <Medal className="w-6 h-6 text-amber-700" />;
    return <span className="text-lg font-bold text-muted-foreground">{rank}</span>;
  };

  const getRankBg = (rank: number) => {
    if (rank === 1) return 'bg-gradient-to-r from-amber-500/20 to-amber-600/20 border-amber-500/30';
    if (rank === 2) return 'bg-gradient-to-r from-gray-400/20 to-gray-500/20 border-gray-400/30';
    if (rank === 3) return 'bg-gradient-to-r from-amber-700/20 to-amber-800/20 border-amber-700/30';
    return 'bg-card border-border';
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-ZA', {
      style: 'currency',
      currency: 'ZAR',
      minimumFractionDigits: 0,
    }).format(amount);
  };

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3, 4, 5].map((i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="h-20 bg-muted rounded" />
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  if (!data) return null;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h2 className="text-3xl font-bold flex items-center gap-2">
            <Trophy className="w-8 h-8 text-amber-500" />
            Contractor Leaderboard
          </h2>
          <p className="text-muted-foreground mt-1">
            Top performers for {new Date(period + '-01').toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}
          </p>
        </div>
        
        <div className="flex gap-3">
          <Select value={metric} onValueChange={setMetric}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="revenue">Revenue</SelectItem>
              <SelectItem value="rating">Customer Rating</SelectItem>
              <SelectItem value="contracts">Contracts Won</SelectItem>
            </SelectContent>
          </Select>

          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Array.from({ length: 12 }, (_, i) => {
                const date = new Date();
                date.setMonth(date.getMonth() - i);
                const value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                return (
                  <SelectItem key={value} value={value}>
                    {date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}
                  </SelectItem>
                );
              })}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total Contractors</p>
                <p className="text-2xl font-bold">{data.stats.totalContractors}</p>
              </div>
              <Users className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Total Revenue</p>
                <p className="text-2xl font-bold">{formatCurrency(data.stats.totalRevenue)}</p>
              </div>
              <DollarSign className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Average Rating</p>
                <p className="text-2xl font-bold flex items-center gap-1">
                  {data.stats.averageRating}
                  <Star className="w-5 h-5 text-amber-500 fill-amber-500" />
                </p>
              </div>
              <Star className="w-8 h-8 text-amber-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Leaderboard */}
      <div className="space-y-3">
        {data.leaderboard.map((entry, index) => {
          const IconComponent = getRankIcon(entry.rank);
          const BadgeIcon = BADGE_ICONS[entry.badges[0]?.badgeType] || Award;
          
          return (
            <motion.div
              key={entry.contractorId}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.05 }}
            >
              <Card className={`border-2 transition-all hover:shadow-lg ${getRankBg(entry.rank)}`}>
                <CardContent className="p-6">
                  <div className="flex items-center gap-4">
                    {/* Rank */}
                    <div className="flex items-center justify-center w-12 h-12 rounded-full bg-background border-2">
                      {IconComponent}
                    </div>

                    {/* Contractor Info */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="text-lg font-bold truncate">
                          {entry.contractorName || entry.companyName}
                        </h3>
                        {entry.isVerified && (
                          <Badge variant="secondary" className="bg-blue-500/10 text-blue-600">
                            <Shield className="w-3 h-3 mr-1" />
                            Verified
                          </Badge>
                        )}
                        {entry.badges.slice(0, 2).map((badge: any) => {
                          const BadgeIconComp = BADGE_ICONS[badge.badgeType] || Award;
                          const badgeColor = BADGE_COLORS[badge.badgeType] || 'bg-gray-500';
                          return (
                            <div
                              key={badge.id}
                              className={`w-6 h-6 rounded-full ${badgeColor} flex items-center justify-center`}
                              title={badge.name}
                            >
                              <BadgeIconComp className="w-3 h-3 text-white" />
                            </div>
                          );
                        })}
                      </div>
                      
                      <div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
                          {entry.averageRating.toFixed(1)} ({entry.reviewCount} reviews)
                        </span>
                        {entry.averageResponseTime && (
                          <span className="flex items-center gap-1">
                            <Clock className="w-4 h-4" />
                            ~{entry.averageResponseTime}h response
                          </span>
                        )}
                        <span className="flex items-center gap-1">
                          <Target className="w-4 h-4" />
                          {entry.conversionRate}% conversion
                        </span>
                      </div>
                    </div>

                    {/* Performance Metrics */}
                    <div className="hidden lg:grid grid-cols-3 gap-6 text-center">
                      <div>
                        <p className="text-2xl font-bold text-green-600">
                          {formatCurrency(entry.revenue)}
                        </p>
                        <p className="text-xs text-muted-foreground">Revenue</p>
                      </div>
                      <div>
                        <p className="text-2xl font-bold text-blue-600">
                          {entry.contractsWon}
                        </p>
                        <p className="text-xs text-muted-foreground">Contracts Won</p>
                      </div>
                      <div>
                        <p className="text-2xl font-bold text-amber-600">
                          {entry.completionRate.toFixed(0)}%
                        </p>
                        <p className="text-xs text-muted-foreground">Completion Rate</p>
                      </div>
                    </div>

                    {/* Mobile Metrics */}
                    <div className="lg:hidden flex flex-col items-end">
                      <p className="text-xl font-bold text-green-600">
                        {formatCurrency(entry.revenue)}
                      </p>
                      <p className="text-sm text-muted-foreground">
                        {entry.contractsWon} contracts
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          );
        })}
      </div>
    </div>
  );
}
