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

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

interface Question {
  id: number;
  frage: string;
  antworten: string[];
  richtigeAntwort: number;
  kategorie: string;
  schwierigkeit: string;
}

interface QuizScreenProps {
  user: any;
  navigation: any;
  route: any;
}

const QuizScreen: React.FC<QuizScreenProps> = ({ user, navigation, route }) => {
  const { profession }: { profession: Profession } = route.params;
  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [showResult, setShowResult] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [showExplanation, setShowExplanation] = useState(false);
  const [correctAnswers, setCorrectAnswers] = useState(0);
  const [wrongAnswers, setWrongAnswers] = useState(0);
  const [quizStarted, setQuizStarted] = useState(false);
  const [quizCompleted, setQuizCompleted] = useState(false);
  const [score, setScore] = useState(0);
  const [fadeAnim] = useState(new Animated.Value(0));
  const [slideAnim] = useState(new Animated.Value(50));

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

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

  const loadQuestionsFromDatabase = async () => {
    try {
      setIsLoading(true);
      console.log(`Loading ${profession} questions from database...`);
      
      // Check if user is authenticated
      const token = apiService.getToken();
      console.log('Current token status:', token ? 'EXISTS' : 'NULL');
      
      if (!token) {
        throw new Error('Sie müssen angemeldet sein, um Fragen zu laden. Bitte melden Sie sich zuerst an.');
      }
      
      // Immer 15-20 Fragen zufällig aus der Datenbank holen
      const questionCount = Math.floor(Math.random() * 6) + 15; // 15-20
      console.log(`Requesting ${questionCount} questions for ${profession}`);
      
      const response = await apiService.getQuestions(profession, questionCount);
      console.log('Raw API response:', response);
      
      // Die API gibt die Fragen direkt als Array zurück, nicht als {data: [...]}
      const questionsData = response || [];
      console.log(`Loaded ${questionsData.length} questions from database`);
      console.log('First question data:', questionsData[0]);
      
      // Map DB structure to frontend structure
      const mappedQuestions = questionsData.map(q => ({
        frage: q.question,
        antworten: [q.option_a, q.option_b, q.option_c, q.option_d],
        richtigeAntwort: q.correct_answer,
        kategorie: categoryParam,
        id: q.id
      }));

      if (questionsData.length === 0) {
        throw new Error('Keine Fragen in der Datenbank gefunden. Bitte versuchen Sie es später erneut.');
      }
      
      // Validate question structure
      const validQuestions = mappedQuestions.filter(q => 
        q && q.frage && q.antworten && q.antworten.length === 4 && q.richtigeAntwort !== undefined && q.kategorie
      );
      
      console.log(`Valid questions: ${validQuestions.length}/${questionsData.length}`);
      
      if (validQuestions.length === 0) {
        throw new Error('Keine gültigen Fragen in der Datenbank gefunden. Die Fragenstruktur ist ungültig.');
      }
      
      setQuestions(validQuestions);
      console.log('Questions set successfully, count:', validQuestions.length);
    } catch (error: any) {
      console.error('Error loading questions from database:', error);
      Alert.alert(
        'Fehler beim Laden der Fragen',
        error.message || 'Fragen konnten nicht aus der Datenbank geladen werden.',
        [
          { text: 'Erneut versuchen', onPress: loadQuestionsFromDatabase },
          { text: 'Zurück', onPress: () => navigation.goBack() }
        ]
      );
    } finally {
      setIsLoading(false);
    }
  };

  const startQuiz = () => {
    setQuizStarted(true);
    loadQuestionsFromDatabase();
  };

  const handleAnswerSelect = (answerIndex: number) => {
    if (showResult || isLoading) return;
    
    setSelectedAnswer(answerIndex);
    setShowResult(true);
    setShowExplanation(true);
    
    const isCorrect = answerIndex === questions[currentQuestionIndex].richtigeAntwort;
    
    if (isCorrect) {
      setCorrectAnswers(prev => prev + 1);
    } else {
      setWrongAnswers(prev => prev + 1);
    }
    
    // Calculate score
    const newScore = Math.round(((correctAnswers + (isCorrect ? 1 : 0)) / (currentQuestionIndex + 1)) * 100);
    setScore(newScore);
  };

  const handleNextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      Animated.timing(slideAnim, {
        toValue: 50,
        duration: 300,
        useNativeDriver: true,
      }).start(() => {
        setCurrentQuestionIndex(prev => prev + 1);
        setSelectedAnswer(null);
        setShowResult(false);
        setShowExplanation(false);
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: true,
        }).start();
      });
    } else {
      completeQuiz();
    }
  };

  const completeQuiz = async () => {
    setQuizCompleted(true);
    
    try {
      console.log('Updating statistics in database...');
      await apiService.updateStatistics({
        beruf: profession,
        correct: correctAnswers,
        wrong: wrongAnswers,
      });
      console.log('Statistics updated successfully');
    } catch (error: any) {
      console.error('Error updating statistics:', error);
      Alert.alert('Warnung', 'Ihre Statistiken konnten nicht aktualisiert werden, aber Ihr Quiz-Ergebnis wurde korrekt berechnet.');
    }
    
    Alert.alert(
      '🎉 Quiz abgeschlossen!',
      `Du hast ${correctAnswers} von ${questions.length} Fragen richtig beantwortet.\nDeine Punktzahl: ${score}%`,
      [
        { text: 'Nochmal spielen', onPress: resetQuiz },
        { text: 'Zurück', onPress: () => navigation.goBack() }
      ]
    );
  };

  const resetQuiz = () => {
    setCurrentQuestionIndex(0);
    setSelectedAnswer(null);
    setShowResult(false);
    setShowExplanation(false);
    setCorrectAnswers(0);
    setWrongAnswers(0);
    setScore(0);
    setQuizCompleted(false);
    setQuizStarted(false);
    loadQuestionsFromDatabase();
  };

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

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

  const getAnswerStyle = (index: number) => {
    if (!showResult) return styles.answerOption;
    
    const isCorrect = index === questions[currentQuestionIndex].richtigeAntwort;
    const isSelected = index === selectedAnswer;
    
    if (isCorrect) return [styles.answerOption, styles.correctAnswer];
    if (isSelected && !isCorrect) return [styles.answerOption, styles.wrongAnswer];
    return styles.answerOption;
  };

  const getAnswerTextStyle = (index: number) => {
    if (!showResult) return styles.answerText;
    
    const isCorrect = index === questions[currentQuestionIndex].richtigeAntwort;
    const isSelected = index === selectedAnswer;
    
    if (isCorrect) return [styles.answerText, styles.correctAnswerText];
    if (isSelected && !isCorrect) return [styles.answerText, styles.wrongAnswerText];
    return styles.answerText;
  };

  if (!quizStarted) {
    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="chevron-back" size={24} color={Colors.text} />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>Quiz Modus</Text>
          <View style={styles.placeholder} />
        </View>

        <Animated.View style={[styles.content, { opacity: fadeAnim, transform: [{ translateY: slideAnim }] }]}>
          <View style={styles.quizStartCard}>
            <Text style={styles.quizIcon}>{getProfessionIcon()}</Text>
            <Text style={styles.quizTitle}>{profession === 'betriebstechnik' ? 'Betriebstechnik' : 'Applikationsentwicklung'}</Text>
            <Text style={styles.quizSubtitle}>15-20 Fragen aus der Datenbank</Text>
            
            <View style={styles.quizInfo}>
              <View style={styles.infoItem}>
                <Text style={styles.infoNumber}>15-20</Text>
                <Text style={styles.infoLabel}>Fragen</Text>
              </View>
              <View style={styles.infoItem}>
                <Text style={styles.infoNumber}>30</Text>
                <Text style={styles.infoLabel}>Sek.</Text>
              </View>
              <View style={styles.infoItem}>
                <Text style={styles.infoNumber}>100%</Text>
                <Text style={styles.infoLabel}>Lernen</Text>
              </View>
            </View>
            
            <TouchableOpacity style={styles.startButton} onPress={startQuiz}>
              <Text style={styles.startButtonText}>Quiz starten</Text>
            </TouchableOpacity>
          </View>
        </Animated.View>
      </SafeAreaView>
    );
  }

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

  const currentQuestion = questions[currentQuestionIndex];
  const progress = questions.length > 0 ? ((currentQuestionIndex + 1) / questions.length) * 100 : 0;

  // Safety check - if no questions or invalid index, show loading
  if (!currentQuestion || questions.length === 0) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="light-content" backgroundColor={Colors.background} />
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>Keine Fragen verfügbar</Text>
          <TouchableOpacity style={styles.retryButton} onPress={loadQuestionsFromDatabase}>
            <Text style={styles.retryButtonText}>Erneut versuchen</Text>
          </TouchableOpacity>
        </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="chevron-back" size={24} color={Colors.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>{profession === 'betriebstechnik' ? 'Betriebstechnik' : 'Applikationsentwicklung'}</Text>
        <Text style={styles.progress}>{currentQuestionIndex + 1}/{questions.length}</Text>
      </View>
      
      <Animated.View style={[styles.content, { transform: [{ translateY: slideAnim }] }]}>
        {/* Progress Bar */}
        <View style={styles.progressContainer}>
          <View 
            style={[
              styles.progressBar,
              { 
                backgroundColor: getProfessionColor(),
                width: `${progress}%`
              }
            ]} 
          />
        </View>
        
        {/* Question Card */}
        <View style={styles.questionCard}>
          <View style={styles.questionHeader}>
            <Text style={styles.questionIcon}>{getProfessionIcon()}</Text>
            <Text style={styles.questionCategory}>{currentQuestion.kategorie}</Text>
            <Text style={styles.difficultyBadge}>{currentQuestion.schwierigkeit}</Text>
          </View>
          <Text style={styles.question}>{currentQuestion.frage}</Text>
        </View>
        
        {/* Answers */}
        <View style={styles.answersContainer}>
          {currentQuestion.antworten.map((answer, index) => (
            <TouchableOpacity
              key={index}
              style={getAnswerStyle(index)}
              onPress={() => handleAnswerSelect(index)}
              disabled={showResult}
            >
              <Text style={getAnswerTextStyle(index)}>{answer}</Text>
              {showResult && index === currentQuestion.richtigeAntwort && (
                <Ionicons name="checkmark-circle" size={20} color={Colors.success} style={styles.answerIcon} />
              )}
              {showResult && selectedAnswer === index && index !== currentQuestion.richtigeAntwort && (
                <Ionicons name="close-circle" size={20} color={Colors.error} style={styles.answerIcon} />
              )}
            </TouchableOpacity>
          ))}
        </View>
        
        {/* Explanation */}
        {showExplanation && (
          <Animated.View style={[styles.explanationCard, { opacity: fadeAnim }]}>
            <Text style={styles.explanationTitle}>
              {selectedAnswer === currentQuestion.richtigeAntwort ? '✅ Richtig!' : '❌ Falsch!'}
            </Text>
            <Text style={styles.explanationText}>
              {selectedAnswer === currentQuestion.richtigeAntwort 
                ? 'Gut gemacht! Diese Antwort ist korrekt.' 
                : `Die richtige Antwort ist: ${currentQuestion.antworten[currentQuestion.richtigeAntwort]}`
              }
            </Text>
          </Animated.View>
        )}
        
        {/* Next Button */}
        {showResult && (
          <TouchableOpacity
            style={[styles.nextButton, { backgroundColor: getProfessionColor() }]}
            onPress={handleNextQuestion}
          >
            <Text style={styles.nextButtonText}>
              {currentQuestionIndex < questions.length - 1 ? 'Nächste Frage →' : 'Quiz beenden →'}
            </Text>
          </TouchableOpacity>
        )}
        
        {/* Score Display */}
        <View style={styles.scoreContainer}>
          <Text style={styles.scoreText}>Punktzahl: {score}%</Text>
          <Text style={styles.scoreSubtext}>{correctAnswers} von {currentQuestionIndex + 1} richtig</Text>
        </View>
      </Animated.View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: Colors.card,
    borderBottomWidth: 1,
    borderBottomColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  backButton: {
    padding: 8,
  },
  placeholder: {
    width: 40,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
  },
  progress: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  progressContainer: {
    height: 4,
    backgroundColor: Colors.border,
    borderRadius: 2,
    marginBottom: 20,
    marginHorizontal: 20,
    overflow: 'hidden',
  },
  progressBar: {
    height: '100%',
    borderRadius: 2,
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
    paddingBottom: 20,
  },
  questionCard: {
    backgroundColor: Colors.card,
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 5,
  },
  questionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  questionIcon: {
    fontSize: 24,
    marginRight: 12,
  },
  questionCategory: {
    fontSize: 14,
    color: Colors.textSecondary,
    backgroundColor: Colors.surface,
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 8,
    marginRight: 8,
  },
  difficultyBadge: {
    fontSize: 12,
    color: Colors.white,
    backgroundColor: Colors.primary,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 6,
  },
  question: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.text,
    lineHeight: 24,
    marginBottom: 8,
  },
  answersContainer: {
    marginBottom: 20,
  },
  answerOption: {
    backgroundColor: Colors.card,
    borderWidth: 1,
    borderColor: Colors.border,
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  correctAnswer: {
    backgroundColor: Colors.success + '20',
    borderColor: Colors.success,
    borderWidth: 2,
  },
  wrongAnswer: {
    backgroundColor: Colors.error + '20',
    borderColor: Colors.error,
    borderWidth: 2,
  },
  answerText: {
    fontSize: 16,
    color: Colors.text,
    flex: 1,
    fontWeight: '500',
  },
  correctAnswerText: {
    color: Colors.success,
    fontWeight: 'bold',
  },
  wrongAnswerText: {
    color: Colors.error,
    fontWeight: 'bold',
  },
  answerIcon: {
    marginLeft: 12,
  },
  nextButton: {
    backgroundColor: Colors.primary,
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    shadowColor: Colors.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 5,
  },
  explanationCard: {
    backgroundColor: Colors.surface,
    borderRadius: 12,
    padding: 16,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: Colors.border,
  },
  explanationTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 8,
  },
  explanationText: {
    fontSize: 14,
    color: Colors.textSecondary,
    lineHeight: 20,
  },
  scoreContainer: {
    alignItems: 'center',
    marginTop: 20,
  },
  scoreText: {
    fontSize: 24,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 4,
  },
  scoreSubtext: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Colors.background,
  },
  loadingText: {
    fontSize: 18,
    color: Colors.text,
  },
  retryButton: {
    backgroundColor: Colors.primary,
    borderRadius: 12,
    paddingVertical: 12,
    paddingHorizontal: 24,
    marginTop: 16,
  },
  retryButtonText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.white,
  },
  quizStartCard: {
    backgroundColor: Colors.card,
    borderRadius: 20,
    padding: 32,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: Colors.border,
    shadowColor: Colors.shadow,
    shadowOffset: { width: 0, height: 8 },
    shadowOpacity: 0.1,
    shadowRadius: 16,
    elevation: 8,
  },
  quizIcon: {
    fontSize: 64,
    marginBottom: 16,
  },
  quizTitle: {
    fontSize: 28,
    fontWeight: 'bold',
    color: Colors.text,
    marginBottom: 8,
    textAlign: 'center',
  },
  quizSubtitle: {
    fontSize: 16,
    color: Colors.textSecondary,
    marginBottom: 32,
    textAlign: 'center',
  },
  quizInfo: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
    marginBottom: 32,
  },
  infoItem: {
    alignItems: 'center',
  },
  infoNumber: {
    fontSize: 24,
    fontWeight: 'bold',
    color: Colors.primary,
    marginBottom: 4,
  },
  infoLabel: {
    fontSize: 14,
    color: Colors.textSecondary,
  },
  startButton: {
    backgroundColor: Colors.primary,
    borderRadius: 12,
    paddingVertical: 16,
    paddingHorizontal: 32,
    shadowColor: Colors.primary,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 5,
  },
  startButtonText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: Colors.white,
  },
  nextButtonText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: Colors.white,
  },
});

export default QuizScreen;
