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;
}

const Leaderboard = ({ limit = 5 }: { limit?: number }) => {
  const [leaderboard, setLeaderboard] = useState<LeaderboardUser[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadLeaderboard = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      // Nur laden, wenn Token vorhanden ist
      const token = apiService.getToken();
      if (!token) {
        console.log('No token found - showing sample leaderboard');
        // Zeige Beispiel-Daten wenn nicht eingeloggt
        setLeaderboard([
          {
            rank: 1,
            username: 'top***',
            firstName: 'Top',
            avatarUrl: undefined,
            totalQuestions: 100,
            correctAnswers: 95,
            bestScore: 98,
            successRate: 95
          },
          {
            rank: 2,
            username: 'pro***',
            firstName: 'Pro',
            avatarUrl: undefined,
            totalQuestions: 85,
            correctAnswers: 78,
            bestScore: 92,
            successRate: 91.76
          },
          {
            rank: 3,
            username: 'usr***',
            firstName: 'User',
            avatarUrl: undefined,
            totalQuestions: 70,
            correctAnswers: 62,
            bestScore: 89,
            successRate: 88.57
          }
        ]);
        return;
      }
      
      const response = await apiService.getLeaderboard(undefined, limit);
      const data = (response as LeaderboardUser[]) || [];
      setLeaderboard(data);
    } catch (error: any) {
      console.error('Error loading leaderboard:', error);
      setError(error.message || 'Fehler beim Laden');
      // Bei Fehler zeige Beispiel-Daten
      setLeaderboard([
        {
          rank: 1,
          username: 'dem***',
          firstName: 'Demo',
          avatarUrl: undefined,
          totalQuestions: 50,
          correctAnswers: 45,
          bestScore: 90,
          successRate: 90
        }
      ]);
    } 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}>
        <Text style={styles.title}>🏆 Top {limit} Leaderboard</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}>
      <Text style={styles.title}>🏆 Top {limit} Leaderboard</Text>
      
      {error && (
        <Text style={styles.errorText}>Zeige Beispiel-Daten</Text>
      )}
      
      {leaderboard.length === 0 ? (
        <View style={styles.emptyContainer}>
          <Text style={styles.emptyText}>Noch keine Einträge</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,
  },
  errorText: {
    fontSize: 12,
    color: Colors.error,
    textAlign: 'center',
    marginBottom: 8,
  },
  emptyContainer: {
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    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;
