import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  SafeAreaView,
  StatusBar,
  Dimensions,
} from 'react-native';
import { DemoGame as GameClass } from './index';
import { GameDifficulty } from '../../core/types';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

interface DemoGameProps {
  message?: string;
  displayTime?: number;
  onGameComplete?: (result: any) => void;
  onGameStart?: () => void;
  showMenu?: boolean;
  autoStart?: boolean;
  title?: string;
  subtitle?: string;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    backgroundColor?: string;
    textColor?: string;
  };
}

export const DemoGameComponent: React.FC<DemoGameProps> = ({
  message = 'HELLO FROM GAMES FOLDER',
  displayTime = 5,
  onGameComplete,
  onGameStart,
  showMenu = true,
  autoStart = false,
  title = '🎮 Demo Game',
  subtitle = 'A simple demo game for testing compatibility',
  theme = {
    primaryColor: '#3498db',
    secondaryColor: '#2ecc71',
    backgroundColor: '#f8f9fa',
    textColor: '#2c3e50'
  }
}) => {
  const [currentScreen, setCurrentScreen] = useState(showMenu ? 'menu' : 'game');
  const [gameInstance, setGameInstance] = useState<any>(null);
  const [gameState, setGameState] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [remainingTime, setRemainingTime] = useState(displayTime);

  useEffect(() => {
    if (autoStart && !showMenu) {
      startGame();
    }
  }, [autoStart, showMenu]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (gameInstance && gameState?.startTime > 0 && !gameState?.isComplete) {
      interval = setInterval(() => {
        const elapsed = gameInstance.getElapsedTime();
        const remaining = gameInstance.getRemainingTime();
        setElapsedTime(elapsed);
        setRemainingTime(remaining);
        
        if (remaining <= 0) {
          clearInterval(interval);
        }
      }, 100);
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [gameInstance, gameState]);

  const startGame = async () => {
    setIsLoading(true);
    try {
      if (!GameClass) {
        console.error('❌ GameClass is undefined!');
        Alert.alert('Error', 'Game class not loaded from library');
        setIsLoading(false);
        return;
      }

      const game = new GameClass();
      
      await game.initialize({
        gameId: 'demo-game',
        difficulty: GameDifficulty.EASY,
        message: message,
        displayTime: displayTime,
        customization: {
          theme: {
            name: 'default',
            colors: {
              primary: theme.primaryColor,
              secondary: theme.secondaryColor,
              background: theme.backgroundColor,
              text: theme.textColor,
            },
          },
        },
        rules: {}
      } as any);

      // Set up event listeners
      (game as any).on('game_completed', (result: any) => {
        console.log('🏁 Demo game complete!', result);
        onGameComplete?.(result);
        
        if (showMenu) {
          Alert.alert(
            '🎉 Demo Complete!',
            `Message displayed: "${message}"\nTime: ${elapsedTime.toFixed(1)}s\nScore: ${result.score}`,
            [
              { text: 'Play Again', onPress: () => startGame() },
              { text: 'Back to Menu', onPress: () => setCurrentScreen('menu') },
            ],
          );
        }
      });

      (game as any).on('game_started', () => {
        console.log('🚀 Demo game started!');
        onGameStart?.();
      });

      setGameInstance(game);
      setGameState(game.getGameState());
      
      await game.start();
      
      setIsLoading(false);
      setCurrentScreen('game');
      
    } catch (error) {
      console.error('❌ Failed to start demo game:', error);
      Alert.alert('Error', 'Failed to start demo game');
      setIsLoading(false);
    }
  };

  const renderMenuScreen = () => (
    <SafeAreaView style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      <StatusBar barStyle="dark-content" backgroundColor={theme.backgroundColor} />
      
      <View style={styles.menuContent}>
        <Text style={[styles.title, { color: theme.textColor }]}>{title}</Text>
        <Text style={[styles.subtitle, { color: theme.textColor }]}>{subtitle}</Text>
        
        <View style={styles.menuButtons}>
          <TouchableOpacity
            style={[styles.button, { backgroundColor: theme.primaryColor }]}
            onPress={startGame}
            disabled={isLoading}
          >
            <Text style={styles.buttonText}>
              {isLoading ? 'Loading...' : 'Start Demo Game'}
            </Text>
          </TouchableOpacity>
        </View>
        
        <View style={styles.gameInfo}>
          <Text style={[styles.infoText, { color: theme.textColor }]}>
            Message: "{message}"
          </Text>
          <Text style={[styles.infoText, { color: theme.textColor }]}>
            Display Time: {displayTime} seconds
          </Text>
        </View>
      </View>
    </SafeAreaView>
  );

  const renderGameScreen = () => (
    <SafeAreaView style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
      <StatusBar barStyle="dark-content" backgroundColor={theme.backgroundColor} />
      
      <View style={styles.gameContent}>
        <View style={styles.header}>
          <Text style={[styles.gameTitle, { color: theme.textColor }]}>Demo Game</Text>
          <Text style={[styles.timer, { color: theme.textColor }]}>
            {remainingTime.toFixed(1)}s remaining
          </Text>
        </View>
        
        <View style={styles.messageContainer}>
          <Text style={[styles.message, { color: theme.textColor }]}>
            {message}
          </Text>
        </View>
        
        <View style={styles.stats}>
          <Text style={[styles.statText, { color: theme.textColor }]}>
            Elapsed: {elapsedTime.toFixed(1)}s
          </Text>
          <Text style={[styles.statText, { color: theme.textColor }]}>
            Score: {gameState?.score || 0}
          </Text>
        </View>
        
        {showMenu && (
          <TouchableOpacity
            style={[styles.backButton, { backgroundColor: theme.secondaryColor }]}
            onPress={() => setCurrentScreen('menu')}
          >
            <Text style={styles.buttonText}>Back to Menu</Text>
          </TouchableOpacity>
        )}
      </View>
    </SafeAreaView>
  );

  if (isLoading) {
    return (
      <SafeAreaView style={[styles.container, { backgroundColor: theme.backgroundColor }]}>
        <View style={styles.loadingContainer}>
          <Text style={[styles.loadingText, { color: theme.textColor }]}>
            Loading Demo Game...
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return currentScreen === 'menu' ? renderMenuScreen() : renderGameScreen();
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  menuContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 10,
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 40,
    opacity: 0.8,
  },
  menuButtons: {
    width: '100%',
    maxWidth: 300,
  },
  button: {
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
    marginBottom: 15,
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  gameInfo: {
    marginTop: 30,
    alignItems: 'center',
  },
  infoText: {
    fontSize: 14,
    marginBottom: 5,
  },
  gameContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  header: {
    alignItems: 'center',
    marginBottom: 40,
  },
  gameTitle: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  timer: {
    fontSize: 18,
    fontWeight: '600',
  },
  messageContainer: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    padding: 30,
    borderRadius: 15,
    marginBottom: 40,
    minWidth: screenWidth * 0.8,
    alignItems: 'center',
  },
  message: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    lineHeight: 32,
  },
  stats: {
    alignItems: 'center',
    marginBottom: 30,
  },
  statText: {
    fontSize: 16,
    marginBottom: 5,
  },
  backButton: {
    padding: 12,
    borderRadius: 8,
    minWidth: 120,
    alignItems: 'center',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    fontSize: 18,
    fontWeight: '600',
  },
}); 