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

interface HomeScreenProps {
  user: any;
  onLogout: () => void;
  navigation: any;
}

const HomeScreen: React.FC<HomeScreenProps> = ({ user, onLogout, navigation }) => {
  console.log('HomeScreen - Current user:', user);
  console.log('HomeScreen - User ID:', user?.id);
  console.log('HomeScreen - Username:', user?.username);
  
  const [statistics, setStatistics] = useState<Statistics>({
    betriebstechnik: { total: 0, richtig: 0, falsch: 0, bestScore: 0 },
    applikationsentwicklung: { total: 0, richtig: 0, falsch: 0, bestScore: 0 }
  });

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

  const loadStatistics = async () => {
    try {
      console.log('HomeScreen - Loading statistics for user:', user?.username, 'ID:', user?.id);
      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('HomeScreen - Raw statistics from API:', statsData);
      
      // Map database field names to frontend field names
      const mappedStats = {
        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('HomeScreen - Mapped statistics for user', user?.username, ':', mappedStats);
      setStatistics(mappedStats);
    } 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();
        // Trigger logout to re-authenticate
        onLogout();
      }
      // Set default statistics on error
      setStatistics({
        betriebstechnik: { total: 0, richtig: 0, falsch: 0, bestScore: 0 },
        applikationsentwicklung: { total: 0, richtig: 0, falsch: 0, bestScore: 0 }
      });
    }
  };

  const handleProfessionSelect = (profession: string) => {
    navigation.navigate('Quiz', { profession });
  };

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="light-content" backgroundColor={Colors.background} />
      
      {/* Header */}
      <View style={styles.header}>
        <View>
          <Text style={styles.logo}>GoLap</Text>
          <Text style={styles.subtitle}>IT-Lehrberufe Lernapp</Text>
        </View>
        <TouchableOpacity style={styles.logoutIconButton} onPress={onLogout}>
          <Ionicons name="log-out-outline" size={24} color={Colors.text} />
        </TouchableOpacity>
      </View>

      {/* Welcome */}
      <View style={styles.welcomeSection}>
        <Text style={styles.welcomeText}>
          Willkommen zurück, {user?.username || user?.first_name || 'User'}!
        </Text>
        <Text style={styles.welcomeSubtext}>
          Wähle deinen Lehrberuf zum Lernen
        </Text>
      </View>

      {/* Profession Cards */}
      <ScrollView style={styles.content}>
        <TouchableOpacity
          style={[styles.card, styles.betriebCard]}
          onPress={() => handleProfessionSelect('betriebstechnik')}
        >
          <View style={styles.cardHeader}>
            <Text style={styles.cardIcon}>🖥️</Text>
            <View style={styles.cardInfo}>
              <Text style={styles.cardTitle}>Betriebstechnik</Text>
              <Text style={styles.cardSubtitle}>Systemtechnik & Netzwerke</Text>
            </View>
          </View>
          <View style={styles.cardStats}>
            <Text style={styles.statItem}>250+ Fragen</Text>
            <Text style={styles.statItem}>10 Themen</Text>
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.card, styles.appCard]}
          onPress={() => handleProfessionSelect('applikationsentwicklung')}
        >
          <View style={styles.cardHeader}>
            <Text style={styles.cardIcon}>💻</Text>
            <View style={styles.cardInfo}>
              <Text style={styles.cardTitle}>Applikationsentwicklung</Text>
              <Text style={styles.cardSubtitle}>Coding & Softwareentwicklung</Text>
            </View>
          </View>
          <View style={styles.cardStats}>
            <Text style={styles.statItem}>200+ Fragen</Text>
            <Text style={styles.statItem}>10 Themen</Text>
          </View>
        </TouchableOpacity>

        {/* User Statistics */}
        <TouchableOpacity
          style={styles.statsCard}
          onPress={() => navigation.navigate('Statistics')}
        >
          <Text style={styles.statsTitle}>📊 Deine Statistiken</Text>
          <Text style={styles.statsSubtitle}>Fortschritt und Erfolge ansehen</Text>
          
          {/* Quick Stats */}
          <View style={styles.quickStats}>
            <View style={styles.quickStatItem}>
              <Text style={styles.quickStatNumber}>{statistics.betriebstechnik.total}</Text>
              <Text style={styles.quickStatLabel}>Betriebstechnik</Text>
            </View>
            <View style={styles.quickStatItem}>
              <Text style={styles.quickStatNumber}>{statistics.applikationsentwicklung.total}</Text>
              <Text style={styles.quickStatLabel}>App-Entwicklung</Text>
            </View>
          </View>
          <Text style={styles.userNote}>Angemeldet als: {user?.username || 'Benutzer'}</Text>
        </TouchableOpacity>

        {/* Leaderboard */}
        <Leaderboard limit={5} />
      
      </ScrollView>

      
     {/* Footer */}
<View style={styles.footer}>
  <Text style={styles.footerText}>
    Entwickelt von aoestudios.at
  </Text>
 
  
</View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.background,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 24,
    paddingTop: 20,
    paddingBottom: 20,
  },
  logo: {
    fontSize: 32,
    fontWeight: 'bold',
    color: Colors.primary,
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  logoutButton: {
    backgroundColor: Colors.error,
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
  },
  logoutText: {
    color: Colors.white,
    fontSize: 14,
    fontWeight: '600',
  },
  logoutIconButton: {
    padding: 8,
    borderRadius: 8,
    backgroundColor: Colors.error + '20',
  },
  welcomeSection: {
    paddingHorizontal: 24,
    paddingVertical: 20,
    alignItems: 'center',
  },
  welcomeText: {
    fontSize: 24,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 8,
  },
  welcomeSubtext: {
    fontSize: 16,
    color: Colors.textSecondary,
    textAlign: 'center',
  },
  content: {
    flex: 1,
    paddingHorizontal: 24,
  },
  card: {
    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,
  },
  betriebCard: {
    borderLeftWidth: 4,
    borderLeftColor: Colors.betriebstechnik.primary,
  },
  appCard: {
    borderLeftWidth: 4,
    borderLeftColor: Colors.applikationsentwicklung.primary,
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  cardIcon: {
    fontSize: 32,
    marginRight: 16,
  },
  cardInfo: {
    flex: 1,
  },
  cardTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 4,
  },
  cardSubtitle: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  cardStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  statItem: {
    fontSize: 12,
    color: Colors.textSecondary,
    backgroundColor: Colors.surface,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
  },
  statsCard: {
    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,
    alignItems: 'center',
    borderLeftWidth: 4,
    borderLeftColor: Colors.primary,
  },
  footerLink: {
  fontSize: 12,
  color: Colors.primary,
  textDecorationLine: 'underline',
  marginBottom: 4,
},
  statsTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 4,
  },
  statsSubtitle: {
    fontSize: 14,
    color: Colors.textSecondary,
    textAlign: 'center',
    marginBottom: 16,
  },
  quickStats: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
  },
  quickStatItem: {
    alignItems: 'center',
  },
  quickStatNumber: {
    fontSize: 20,
    fontWeight: 'bold',
    color: Colors.primary,
    marginBottom: 4,
  },
  quickStatLabel: {
    fontSize: 12,
    color: Colors.textSecondary,
    textAlign: 'center',
  },
  userNote: {
    fontSize: 10,
    color: Colors.textSecondary,
    textAlign: 'center',
    marginTop: 8,
    fontStyle: 'italic',
  },
  leaderboardCard: {
    backgroundColor: Colors.warning,
    borderRadius: 16,
    padding: 20,
    marginBottom: 16,
    alignItems: 'center',
  },
  leaderboardTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.white,
    marginBottom: 4,
  },
  leaderboardSubtitle: {
    fontSize: 14,
    color: Colors.white,
    opacity: 0.9,
    textAlign: 'center',
    marginBottom: 16,
  },
  leaderboardPreview: {
    backgroundColor: Colors.white,
    borderRadius: 8,
    padding: 8,
    width: '100%',
  },
  leaderboardPreviewText: {
    fontSize: 12,
    color: Colors.warning,
    textAlign: 'center',
    fontWeight: '600',
  },
  footer: {
    alignItems: 'center',
    paddingBottom: 20,
  },
  footerText: {
    fontSize: 14,
    color: Colors.textSecondary,
    marginBottom: 8,
  },
  apiStatus: {
    fontSize: 12,
    color: Colors.success,
  },
});

export default HomeScreen;