import { Ionicons } from '@expo/vector-icons';
import React, { useEffect, useRef, useState } from 'react';
import {
    Alert,
    Animated,
    Dimensions,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Colors } from '../constants/colors';
import { Statistics } from '../types';
import { apiService } from '../utils/api';

const { width } = Dimensions.get('window');

interface StatisticsScreenProps {
  navigation: any;
  route: any;
}

const StatisticsScreen: React.FC<StatisticsScreenProps> = ({ navigation, route }) => {
  const [user, setUser] = useState<any>(null);
  const [statistics, setStatistics] = useState<Statistics>({
    betriebstechnik: { total: 0, richtig: 0, falsch: 0, bestScore: 0 },
    applikationsentwicklung: { total: 0, richtig: 0, falsch: 0, bestScore: 0 }
  });
  const [quizHistory, setQuizHistory] = useState<any[]>([]);
  const [showHistory, setShowHistory] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const fadeAnim = useRef(new Animated.Value(0)).current;

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

  const loadUserData = async () => {
    try {
      console.log('StatisticsScreen - Loading user data...');
      const profileResponse = await apiService.getProfile();
      const userData = profileResponse; // Die API gibt direkt die User-Daten zurück
      console.log('StatisticsScreen - User data loaded:', userData);
      setUser(userData);
    } catch (error: any) {
      console.error('Error loading user data:', error);
      // Clear token and reload if token is invalid
      if (error.message?.includes('Token')) {
        console.log('Clearing invalid token...');
        await apiService.clearToken();
        // Navigate back to login
        navigation.navigate('Login');
      }
      setIsLoading(false);
    }
  };

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

  useEffect(() => {
    if (user) {
      loadStatistics();
    }
  }, [user]);

  const animateEntrance = () => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 600,
      useNativeDriver: true,
    }).start();
  };

  const loadQuizHistory = async () => {
    try {
      console.log('StatisticsScreen - Loading quiz history...');
      const response = await apiService.getQuizHistory();
      // Die API gibt die Historie direkt als Array zurück, nicht als {data: [...]}
      const history = response || [];
      console.log('StatisticsScreen - Quiz history loaded:', history);
      setQuizHistory(history);
    } catch (error: any) {
      console.error('Error loading quiz history:', error);
      // Quiz history is optional, don't show error to user
      setQuizHistory([]);
    }
  };

  const loadStatistics = async () => {
    try {
      console.log('StatisticsScreen - Loading statistics for user:', user?.username, 'ID:', user?.id);
      setIsLoading(true);
      const response = await apiService.getStatistics();
      const statsData = (response as any).data || {
        betriebstechnik: { total: 0, richtig: 0, falsch: 0, bestScore: 0 },
        applikationsentwicklung: { total: 0, richtig: 0, falsch: 0, bestScore: 0 }
      };
      
      console.log('StatisticsScreen - Raw statistics from API:', statsData);
      
      // Map database field names to frontend field names
      const userStats = {
        betriebstechnik: {
          total: statsData.betriebstechnik?.total || 0,
          richtig: statsData.betriebstechnik?.richtig || 0,
          falsch: statsData.betriebstechnik?.falsch || 0,
          bestScore: statsData.betriebstechnik?.bestScore || 0
        },
        applikationsentwicklung: {
          total: statsData.applikationsentwicklung?.total || 0,
          richtig: statsData.applikationsentwicklung?.richtig || 0,
          falsch: statsData.applikationsentwicklung?.falsch || 0,
          bestScore: statsData.applikationsentwicklung?.bestScore || 0
        }
      };
      
      console.log('StatisticsScreen - Mapped statistics for user', user?.username, ':', userStats);
      console.log('StatisticsScreen - Betriebstechnik total:', userStats.betriebstechnik.total);
      console.log('StatisticsScreen - App-Entwicklung total:', userStats.applikationsentwicklung.total);
      setStatistics(userStats);
      
      // Load quiz history after statistics
      await loadQuizHistory();
    } catch (error: any) {
      console.error('Error loading statistics:', error);
      // Clear token and reload if token is invalid
      if (error.message?.includes('Token')) {
        console.log('Clearing invalid token...');
        await apiService.clearToken();
        // Navigate back to login
        navigation.navigate('Login');
      }
      Alert.alert('Fehler', 'Statistiken konnten nicht geladen werden');
      // Set default statistics on error
      setStatistics({
        betriebstechnik: { total: 0, richtig: 0, falsch: 0, bestScore: 0 },
        applikationsentwicklung: { total: 0, richtig: 0, falsch: 0, bestScore: 0 }
      });
    } finally {
      setIsLoading(false);
    }
  };

  const resetStatistics = () => {
    Alert.alert(
      'Statistiken zurücksetzen',
      'Möchtest du wirklich alle deine Statistiken zurücksetzen?',
      [
        { text: 'Abbrechen', style: 'cancel' },
        { 
          text: 'Zurücksetzen', 
          style: 'destructive',
          onPress: async () => {
            try {
              // Reset statistics in database via API
              await apiService.resetStatistics();
              // Reload fresh statistics from database
              await loadStatistics();
              Alert.alert('Erfolg', 'Statistiken wurden zurückgesetzt');
            } catch (error: any) {
              console.error('Error resetting statistics:', error);
              // Clear token and reload if token is invalid
              if (error.message?.includes('Token')) {
                console.log('Clearing invalid token...');
                await apiService.clearToken();
                // Navigate back to login
                navigation.navigate('Login');
              }
              Alert.alert('Fehler', 'Statistiken konnten nicht zurückgesetzt werden');
            }
          }
        }
      ]
    );
  };

  const getSuccessRate = (correct: number, total: number) => {
    if (total === 0) return 0;
    return Math.round((correct / total) * 100);
  };

  const getProfessionColor = (profession: string) => {
    return profession === 'betriebstechnik' ? Colors.betriebstechnik.primary : Colors.applikationsentwicklung.primary;
  };

  const getProfessionIcon = (profession: string) => {
    return profession === 'betriebstechnik' ? '🖥️' : '💻';
  };

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="light-content" backgroundColor={Colors.background} />
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>Lade Statistiken...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="light-content" backgroundColor={Colors.background} />
      
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={() => navigation.goBack()}>
          <Ionicons name="arrow-back" size={24} color={Colors.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Statistiken</Text>
        <View style={styles.headerButtons}>
          <TouchableOpacity style={styles.refreshButton} onPress={loadStatistics}>
            <Ionicons name="refresh" size={24} color={Colors.primary} />
          </TouchableOpacity>
          <TouchableOpacity style={styles.historyButton} onPress={() => setShowHistory(!showHistory)}>
            <Ionicons name="time" size={24} color={Colors.primary} />
          </TouchableOpacity>
          <TouchableOpacity style={styles.resetButton} onPress={resetStatistics}>
            <Ionicons name="trash" size={24} color={Colors.error} />
          </TouchableOpacity>
        </View>
      </View>

      <ScrollView 
        style={styles.scrollView}
        contentContainerStyle={styles.scrollViewContent}
        showsVerticalScrollIndicator={true}
      >
        <Animated.View style={[styles.content, { opacity: fadeAnim }]}>
          {/* User Info */}
          <View style={styles.userCard}>
            <Text style={styles.userName}>{user?.username || 'Benutzer'}</Text>
            <Text style={styles.userEmail}>{user?.email}</Text>
            <Text style={styles.userJoinDate}>Mitglied seit {user?.created_at ? new Date(user.created_at).toLocaleDateString('de-DE', { 
              year: 'numeric', 
              month: 'long', 
              day: 'numeric' 
            }) : 'Unbekannt'}</Text>
          </View>

        {/* Overall Stats */}
        <View style={styles.overallCard}>
          <Text style={styles.overallTitle}>📊 Gesamtstatistik</Text>
          <View style={styles.overallStats}>
            <View style={styles.overallStatItem}>
              <Text style={styles.overallStatNumber}>
                {statistics.betriebstechnik.total + statistics.applikationsentwicklung.total}
              </Text>
              <Text style={styles.overallStatLabel}>Gesamte Fragen</Text>
            </View>
            <View style={styles.overallStatItem}>
              <Text style={styles.overallStatNumber}>
                {statistics.betriebstechnik.richtig + statistics.applikationsentwicklung.richtig}
              </Text>
              <Text style={styles.overallStatLabel}>Richtig</Text>
            </View>
            <View style={styles.overallStatItem}>
              <Text style={styles.overallStatNumber}>
                {getSuccessRate(
                  statistics.betriebstechnik.richtig + statistics.applikationsentwicklung.richtig,
                  statistics.betriebstechnik.total + statistics.applikationsentwicklung.total
                )}%
              </Text>
              <Text style={styles.overallStatLabel}>Erfolgsrate</Text>
            </View>
          </View>
        </View>

        {/* Betriebstechnik Stats */}
        <View style={styles.professionCard}>
          <View style={styles.professionHeader}>
            <Text style={styles.professionIcon}>🖥️</Text>
            <Text style={styles.professionTitle}>Betriebstechnik</Text>
          </View>
          <View style={styles.professionStats}>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Beantwortet:</Text>
              <Text style={styles.statValue}>{statistics.betriebstechnik.total}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Richtig:</Text>
              <Text style={[styles.statValue, { color: Colors.success }]}>{statistics.betriebstechnik.richtig}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Falsch:</Text>
              <Text style={[styles.statValue, { color: Colors.error }]}>{statistics.betriebstechnik.falsch}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Erfolgsrate:</Text>
              <Text style={[styles.statValue, { color: Colors.betriebstechnik.primary }]}>
                {getSuccessRate(statistics.betriebstechnik.richtig, statistics.betriebstechnik.total)}%
              </Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Beste Punktzahl:</Text>
              <Text style={[styles.statValue, { color: Colors.betriebstechnik.primary }]}>
                {statistics.betriebstechnik.bestScore || 0}%
              </Text>
            </View>
          </View>
          <View style={styles.progressBar}>
            <View 
              style={[
                styles.progressFill,
                { 
                  width: `${getSuccessRate(statistics.betriebstechnik.richtig, statistics.betriebstechnik.total)}%`,
                  backgroundColor: Colors.betriebstechnik.primary
                }
              ]} 
            />
          </View>
        </View>

        {/* Applikationsentwicklung Stats */}
        <View style={styles.professionCard}>
          <View style={styles.professionHeader}>
            <Text style={styles.professionIcon}>💻</Text>
            <Text style={styles.professionTitle}>Applikationsentwicklung</Text>
          </View>
          <View style={styles.professionStats}>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Beantwortet:</Text>
              <Text style={styles.statValue}>{statistics.applikationsentwicklung.total}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Richtig:</Text>
              <Text style={[styles.statValue, { color: Colors.success }]}>{statistics.applikationsentwicklung.richtig}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Falsch:</Text>
              <Text style={[styles.statValue, { color: Colors.error }]}>{statistics.applikationsentwicklung.falsch}</Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Erfolgsrate:</Text>
              <Text style={[styles.statValue, { color: Colors.applikationsentwicklung.primary }]}>
                {getSuccessRate(statistics.applikationsentwicklung.richtig, statistics.applikationsentwicklung.total)}%
              </Text>
            </View>
            <View style={styles.statRow}>
              <Text style={styles.statLabel}>Beste Punktzahl:</Text>
              <Text style={[styles.statValue, { color: Colors.applikationsentwicklung.primary }]}>
                {statistics.applikationsentwicklung.bestScore || 0}%
              </Text>
            </View>
          </View>
          <View style={styles.progressBar}>
            <View 
              style={[
                styles.progressFill,
                { 
                  width: `${getSuccessRate(statistics.applikationsentwicklung.richtig, statistics.applikationsentwicklung.total)}%`,
                  backgroundColor: Colors.applikationsentwicklung.primary
                }
              ]} 
            />
          </View>
        </View>

        {/* Quiz History */}
        {showHistory && (
          <View style={styles.historyCard}>
            <Text style={styles.historyTitle}>📝 Kürzliche Quiz-Sessions</Text>
            {quizHistory.length > 0 ? (
              quizHistory.slice(0, 5).map((session, index) => (
                <View key={index} style={styles.historyItem}>
                  <View style={styles.historyItemLeft}>
                    <Text style={styles.historyDate}>
                      {new Date(session.completed_at).toLocaleDateString('de-DE')}
                    </Text>
                    <Text style={styles.historyProfession}>{session.beruf}</Text>
                  </View>
                  <View style={styles.historyItemRight}>
                    <Text style={styles.historyScore}>{session.score_percentage}%</Text>
                    <Text style={styles.historyQuestions}>
                      {session.correct_answers}/{session.total_questions}
                    </Text>
                  </View>
                </View>
              ))
            ) : (
              <Text style={styles.noHistoryText}>Noch keine Quiz-Sessions vorhanden</Text>
            )}
          </View>
        )}
        </Animated.View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollViewContent: {
    padding: 20,
    paddingBottom: 40,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: Colors.card,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
  },
  backButton: {
    padding: 8,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
  },
  resetButton: {
    padding: 8,
  },
  headerButtons: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  refreshButton: {
    padding: 8,
    marginRight: 8,
  },
  historyButton: {
    padding: 8,
    marginRight: 8,
  },
  content: {
    // Entfernt padding, da scrollViewContent verwendet wird
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 18,
    color: Colors.text,
  },
  userCard: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: Colors.border,
    alignItems: 'center',
  },
  userName: {
    fontSize: 20,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 4,
  },
  userEmail: {
    fontSize: 14,
    color: Colors.textSecondary,
    marginBottom: 4,
  },
  userJoinDate: {
    fontSize: 12,
    color: Colors.textSecondary,
  },
  overallCard: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
    borderLeftWidth: 4,
    borderLeftColor: Colors.primary,
  },
  overallTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 16,
  },
  overallStats: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
  },
  overallStatItem: {
    alignItems: 'center',
  },
  overallStatNumber: {
    fontSize: 24,
    fontWeight: 'bold',
    color: Colors.primary,
    marginBottom: 4,
  },
  overallStatLabel: {
    fontSize: 12,
    color: Colors.textSecondary,
    textAlign: 'center',
  },
  professionCard: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: Colors.border,
  },
  professionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  professionIcon: {
    fontSize: 24,
    marginRight: 12,
  },
  professionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
  },
  professionStats: {
    marginBottom: 16,
  },
  statRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  statLabel: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  statValue: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.text,
  },
  progressBar: {
    height: 8,
    backgroundColor: Colors.border,
    borderRadius: 4,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    borderRadius: 4,
  },
  historyCard: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
    borderLeftWidth: 4,
    borderLeftColor: Colors.primary,
  },
  historyTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 16,
  },
  historyItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
  },
  historyItemLeft: {
    flex: 1,
  },
  historyDate: {
    fontSize: 14,
    color: Colors.text,
    fontWeight: '500',
  },
  historyProfession: {
    fontSize: 12,
    color: Colors.textSecondary,
    marginTop: 2,
  },
  historyItemRight: {
    alignItems: 'flex-end',
  },
  historyScore: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.primary,
  },
  historyQuestions: {
    fontSize: 12,
    color: Colors.textSecondary,
    marginTop: 2,
  },
  noHistoryText: {
    fontSize: 14,
    color: Colors.textSecondary,
    textAlign: 'center',
    fontStyle: 'italic',
    paddingVertical: 20,
  },
});

export default StatisticsScreen;