import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  SafeAreaView,
  StatusBar,
  ScrollView,
} from 'react-native';

import { DemoGameComponent } from './DemoGameComponent';
import { GameManager } from '../../services/GameManager';

export const DemoGameTestApp: React.FC = () => {
  const [currentView, setCurrentView] = useState<'menu' | 'game' | 'manager'>('menu');
  const [gameManager, setGameManager] = useState<any>(null);
  const [availableGames, setAvailableGames] = useState<any[]>([]);
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    const initializeManager = async () => {
      try {
        const manager = GameManager.getInstance();
        await manager.initialize({
          enableAnalytics: true,
          enableStorage: true,
          allowedGames: ['demo-game', 'memory-match', 'reaction-time'],
          defaultTheme: {
            name: 'default',
            colors: {
              primary: '#3498db',
              secondary: '#2ecc71',
              accent: '#e74c3c',
              background: '#f8f9fa',
              surface: '#ffffff',
              text: '#2c3e50',
              textSecondary: '#7f8c8d',
              success: '#27ae60',
              warning: '#f39c12',
              error: '#e74c3c',
            },
            fonts: {
              regular: 'System',
              bold: 'System',
              title: 'System',
            },
            spacing: {
              xs: 4,
              sm: 8,
              md: 16,
              lg: 24,
              xl: 32,
            },
          },
          customization: {
            brandName: 'Demo Games',
            primaryColor: '#3498db',
            defaultLanguage: 'en'
          }
        });
        manager.setPlayer({
          playerId: 'demo_player_' + Date.now(),
          firstName: 'Demo',
          lastName: 'Player',
          createdAt: new Date(),
          lastActive: new Date(),
          totalGamesPlayed: 0,
          achievements: []
        });
        setGameManager(manager);
        setAvailableGames(manager.getAvailableGames());
        setIsInitialized(true);
        console.log('✅ Game Manager initialized successfully');
        console.log('📋 Available games:', manager.getAvailableGames());
      } catch (error) {
        console.error('❌ Failed to initialize game manager:', error);
        Alert.alert('Error', 'Failed to initialize game manager');
      }
    };
    initializeManager();
  }, []);

  const testGameManager = async () => {
    if (!gameManager) {
      Alert.alert('Error', 'Game manager not initialized');
      return;
    }
    try {
      const game = await gameManager.launchGame('demo-game', {
        message: 'HELLO FROM GAMES FOLDER - MANAGER TEST',
        displayTime: 3
      });
      Alert.alert(
        'Success',
        `Demo game launched successfully!\nGame ID: ${game.gameId}\nName: ${game.name}`
      );
      setTimeout(() => {
        const result = gameManager.endGame('demo-game');
        console.log('🏁 Game result:', result);
      }, 4000);
    } catch (error) {
      console.error('❌ Failed to launch demo game:', error);
      Alert.alert('Error', 'Failed to launch demo game');
    }
  };

  const renderMenu = () => (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#f8f9fa" />
      <View style={styles.header}>
        <Text style={styles.title}>🎮 Demo Game Test</Text>
        <Text style={styles.subtitle}>Testing compatibility and functionality</Text>
      </View>
      <ScrollView style={styles.content}>
        <View style={styles.statusSection}>
          <Text style={styles.sectionTitle}>System Status</Text>
          <Text style={[styles.statusText, { color: isInitialized ? '#27ae60' : '#e74c3c' }]}> {isInitialized ? '✅ Initialized' : '⏳ Initializing...'} </Text>
          <Text style={styles.statusText}> Available Games: {availableGames.length} </Text>
        </View>
        <View style={styles.buttonSection}>
          <Text style={styles.sectionTitle}>Test Options</Text>
          <TouchableOpacity style={[styles.button, styles.primaryButton]} onPress={() => setCurrentView('game')}>
            <Text style={styles.buttonText}>🎯 Test Demo Game Component</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.button, styles.secondaryButton]} onPress={() => setCurrentView('manager')}>
            <Text style={styles.buttonText}>⚙️ Test Game Manager</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.button, styles.infoButton]} onPress={testGameManager}>
            <Text style={styles.buttonText}>🚀 Launch via Manager</Text>
          </TouchableOpacity>
        </View>
        {availableGames.length > 0 && (
          <View style={styles.gamesSection}>
            <Text style={styles.sectionTitle}>Available Games</Text>
            {availableGames.map((game, index) => (
              <View key={index} style={styles.gameItem}>
                <Text style={styles.gameName}>{game.name}</Text>
                <Text style={styles.gameDescription}>{game.description}</Text>
                <Text style={styles.gameId}>ID: {game.id}</Text>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );

  const renderDemoGame = () => (
    <DemoGameComponent
      message="HELLO FROM GAMES FOLDER"
      displayTime={5}
      showMenu={true}
      autoStart={false}
      title="🎮 Demo Game Test"
      subtitle="Testing the demo game component"
      onGameComplete={(result) => {
        console.log('🏁 Demo game completed:', result);
        Alert.alert(
          'Demo Complete!',
          `Message: "${result.customData?.message}"\nScore: ${result.score}\nTime: ${result.timeSpent.toFixed(1)}s`,
          [{ text: 'OK', onPress: () => setCurrentView('menu') }]
        );
      }}
      onGameStart={() => {
        console.log('🚀 Demo game started!');
      }}
    />
  );

  const renderManagerTest = () => (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#f8f9fa" />
      <View style={styles.header}>
        <Text style={styles.title}>⚙️ Game Manager Test</Text>
        <Text style={styles.subtitle}>Testing game manager functionality</Text>
      </View>
      <ScrollView style={styles.content}>
        <View style={styles.statusSection}>
          <Text style={styles.sectionTitle}>Manager Status</Text>
          <Text style={styles.statusText}> Initialized: {isInitialized ? 'Yes' : 'No'} </Text>
          <Text style={styles.statusText}> Available Games: {availableGames.length} </Text>
          <Text style={styles.statusText}> Player ID: {gameManager?.getPlayer()?.playerId || 'None'} </Text>
        </View>
        <View style={styles.buttonSection}>
          <Text style={styles.sectionTitle}>Manager Actions</Text>
          <TouchableOpacity style={[styles.button, styles.primaryButton]} onPress={testGameManager}>
            <Text style={styles.buttonText}>🚀 Launch Demo Game</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.button, styles.secondaryButton]} onPress={async () => {
            try {
              const history = await gameManager?.getGameHistory();
              Alert.alert('Game History', `Found ${history?.length || 0} game results`);
            } catch (error) {
              Alert.alert('Error', 'Failed to get game history');
            }
          }}>
            <Text style={styles.buttonText}>📊 Get Game History</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.button, styles.infoButton]} onPress={() => setCurrentView('menu')}>
            <Text style={styles.buttonText}>🔙 Back to Menu</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );

  switch (currentView) {
    case 'game':
      return renderDemoGame();
    case 'manager':
      return renderManagerTest();
    default:
      return renderMenu();
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f8f9fa',
  },
  header: {
    padding: 20,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#e9ecef',
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#2c3e50',
    marginBottom: 5,
  },
  subtitle: {
    fontSize: 16,
    color: '#7f8c8d',
    textAlign: 'center',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  statusSection: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#2c3e50',
    marginBottom: 10,
  },
  statusText: {
    fontSize: 14,
    color: '#7f8c8d',
    marginBottom: 5,
  },
  buttonSection: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  button: {
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
    marginBottom: 10,
  },
  primaryButton: {
    backgroundColor: '#3498db',
  },
  secondaryButton: {
    backgroundColor: '#2ecc71',
  },
  infoButton: {
    backgroundColor: '#9b59b6',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  gamesSection: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  gameItem: {
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#f1f2f6',
  },
  gameName: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#2c3e50',
    marginBottom: 5,
  },
  gameDescription: {
    fontSize: 14,
    color: '#7f8c8d',
    marginBottom: 3,
  },
  gameId: {
    fontSize: 12,
    color: '#95a5a6',
    fontFamily: 'monospace',
  },
});

export default DemoGameTestApp; 