import { Ionicons } from '@expo/vector-icons';
import React, { useEffect, useState } from 'react';
import {
    ActivityIndicator,
    StyleSheet,
    Text,
    View
} from 'react-native';
import { Colors } from '../constants/colors';
import { apiService } from '../utils/api';

interface LeaderboardUser {
  rank: number;
  username: string;
  firstName: string;
  avatarUrl?: string;
  totalQuestions: number;
  correctAnswers: number;
  bestScore: number;
  successRate: number;
}

interface LeaderboardProps {
  beruf?: string;
  limit?: number;
  showTitle?: boolean;
}

const Leaderboard: React.FC<LeaderboardProps> = ({ 
  beruf, 
  limit = 5, 
  showTitle = true 
}) => {
  const [leaderboard, setLeaderboard] = useState<LeaderboardUser[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    loadLeaderboard();
  }, [beruf]);

  const loadLeaderboard = async () => {
    try {
      setIsLoading(true);
      const response = await apiService.getLeaderboard(beruf, limit);
      const data = (response as LeaderboardUser[]) || [];
      setLeaderboard(data);
    } catch (error) {
      console.error('Error loading leaderboard:', error);
      setLeaderboard([]);
    } finally {
      setIsLoading(false);
    }
  };

  const getRankIcon = (rank: number) => {
    switch (rank) {
      case 1: return '🥇';
      case 2: return '🥈';
      case 3: return '🥉';
      default: return `#${rank}`;
    }
  };

  const getRankColor = (rank: number) => {
    switch (rank) {
      case 1: return Colors.warning;
      case 2: return '#C0C0C0';
      case 3: return '#CD7F32';
      default: return Colors.textSecondary;
    }
  };

  if (isLoading) {
    return (
      <View style={styles.container}>
        {showTitle && (
          <Text style={styles.title}>
            🏆 Top {limit} {beruf ? `(${beruf === 'betriebstechnik' ? 'Betriebstechnik' : 'App-Entwicklung'})` : 'Gesamt'}
          </Text>
        )}
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="small" color={Colors.primary} />
          <Text style={styles.loadingText}>Lade Leaderboard...</Text>
        </View>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {showTitle && (
        <Text style={styles.title}>
          🏆 Top {limit} {beruf ? `(${beruf === 'betriebstechnik' ? 'Betriebstechnik' : 'App-Entwicklung'})` : 'Gesamt'}
        </Text>
      )}
      
      {leaderboard.length === 0 ? (
        <View style={styles.emptyContainer}>
          <Ionicons name="trophy" size={40} color={Colors.textSecondary} />
          <Text style={styles.emptyText}>Noch keine Einträge im Leaderboard</Text>
        </View>
      ) : (
        <View style={styles.leaderboardList}>
          {leaderboard.map((user) => (
            <View key={user.rank} style={styles.leaderboardItem}>
              <View style={styles.rankContainer}>
                <Text style={[styles.rank, { color: getRankColor(user.rank) }]}>
                  {getRankIcon(user.rank)}
                </Text>
              </View>
              
              <View style={styles.userInfo}>
                <Text style={styles.username}>{user.username}</Text>
                <Text style={styles.firstName}>{user.firstName}</Text>
              </View>
              
              <View style={styles.stats}>
                <Text style={styles.score}>{user.bestScore}%</Text>
                <Text style={styles.questions}>
                  {user.correctAnswers}/{user.totalQuestions}
                </Text>
              </View>
            </View>
          ))}
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 16,
    marginVertical: 12,
    borderWidth: 1,
    borderColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 12,
    textAlign: 'center',
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
  },
  loadingText: {
    marginLeft: 8,
    fontSize: 14,
    color: Colors.textSecondary,
  },
  emptyContainer: {
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    marginTop: 8,
    fontSize: 14,
    color: Colors.textSecondary,
    textAlign: 'center',
  },
  leaderboardList: {
    gap: 8,
  },
  leaderboardItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: Colors.background,
    borderRadius: 12,
    padding: 12,
    borderWidth: 1,
    borderColor: Colors.border,
  },
  rankContainer: {
    width: 40,
    alignItems: 'center',
  },
  rank: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  userInfo: {
    flex: 1,
    marginLeft: 12,
  },
  username: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.text,
  },
  firstName: {
    fontSize: 12,
    color: Colors.textSecondary,
    marginTop: 2,
  },
  stats: {
    alignItems: 'flex-end',
  },
  score: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.primary,
  },
  questions: {
    fontSize: 12,
    color: Colors.textSecondary,
    marginTop: 2,
  },
});

export default Leaderboard;
