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

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

interface MemoryMatchGameProps {
  gridSize?: number;
  difficulty?: 'easy' | 'medium' | 'hard' | 'expert';
  onGameComplete?: (result: any) => void;
  onGameStart?: () => void;
  onCardFlip?: (cardData: any) => void;
  showMenu?: boolean;
  autoStart?: boolean;
  title?: string;
  subtitle?: string;
  showStats?: boolean;
  enableHints?: boolean;
  enableReset?: boolean;
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    backgroundColor?: string;
    textColor?: string;
    cardColor?: string;
    matchedColor?: string;
  };
}

export const MemoryMatchGameComponent: React.FC<MemoryMatchGameProps> = ({
  gridSize = 4,
  difficulty = 'easy',
  onGameComplete,
  onGameStart,
  onCardFlip,
  showMenu = true,
  autoStart = false,
  title = '🧠 משחק זיכרון',
  subtitle = 'מצא את הזוגות התואמים!',
  showStats = true,
  enableHints = true,
  enableReset = true,
  theme = {
    primaryColor: '#3498db',
    secondaryColor: '#2ecc71',
    backgroundColor: '#f8f9fa',
    textColor: '#2c3e50',
    cardColor: '#ffffff',
    matchedColor: '#27ae60'
  }
}) => {
  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 [gameStats, setGameStats] = useState({
    matches: 0,
    attempts: 0,
    time: 0,
    isComplete: false,
  });
  
  const [internalStats, setInternalStats] = useState({
    totalGames: 0,
    bestScore: 0,
    bestTime: 0,
    totalMatches: 0,
    averageAttempts: 0,
  });

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

  const startGame = async () => {
    setIsLoading(true);
    try {
      if (!GameClass) {
        console.error('❌ GameClass is undefined!');
        Alert.alert('שגיאה', 'מחלקת המשחק לא נטענה מהספרייה');
        setIsLoading(false);
        return;
      }

      const game = new GameClass();
      
      let gameDifficulty: GameDifficulty;
      switch (difficulty) {
        case 'easy':
          gameDifficulty = GameDifficulty.EASY;
          break;
        case 'medium':
          gameDifficulty = GameDifficulty.MEDIUM;
          break;
        case 'hard':
          gameDifficulty = GameDifficulty.HARD;
          break;
        case 'expert':
          gameDifficulty = GameDifficulty.EXPERT;
          break;
        default:
          gameDifficulty = GameDifficulty.EASY;
      }

      await game.initialize({
        gameId: 'memory-match',
        gridSize,
        difficulty: gameDifficulty,
        customization: {
          theme: {
            name: 'default',
            colors: {
              primary: theme.primaryColor,
              secondary: theme.secondaryColor,
              background: theme.backgroundColor,
              text: theme.textColor,
              card: theme.cardColor,
              matched: theme.matchedColor,
            },
          },
        },
        rules: {}
      } as any);

      (game as any).on('cardFlip', (cardData: any) => {
        console.log('🔄 Card flipped:', cardData);
        updateGameStats(game);
        onCardFlip?.(cardData);
      });

      (game as any).on('gameComplete', (result: any) => {
        console.log('🏁 Memory game complete!', result);
        
        const newTotalGames = internalStats.totalGames + 1;
        const newTotalMatches = internalStats.totalMatches + result.customData?.matches || 0;
        const newAverageAttempts = Math.round((internalStats.averageAttempts * (newTotalGames - 1) + result.customData?.attempts) / newTotalGames);
        
        setInternalStats(prev => ({
          totalGames: newTotalGames,
          bestScore: Math.max(prev.bestScore, result.score || 0),
          bestTime: prev.bestTime === 0 ? result.timeSpent : Math.min(prev.bestTime, result.timeSpent || 0),
          totalMatches: newTotalMatches,
          averageAttempts: newAverageAttempts,
        }));
        
        onGameComplete?.(result);
        
        if (showMenu) {
          Alert.alert(
            '🎉 כל הכבוד!',
            `השלמת את משחק הזיכרון!\n` +
              `זוגות שנמצאו: ${result.customData?.matches || 0}\n` +
              `ניסיונות: ${result.customData?.attempts || 0}\n` +
              `זמן: ${Math.floor(result.timeSpent / 1000)}s\n` +
              `ניקוד: ${result.score}`,
            [
              { text: 'משחק חדש', onPress: () => startGame() },
              { text: 'חזור לתפריט', onPress: () => setCurrentScreen('menu') },
            ],
          );
        }
      });

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

      setGameInstance(game);
      setGameState(game.getMemoryState());
      
      await game.start();
      
      setIsLoading(false);
      setCurrentScreen('game');
      
    } catch (error) {
      console.error('❌ Failed to start memory game:', error);
      Alert.alert('שגיאה', 'נכשל בהתחלת משחק הזיכרון');
      setIsLoading(false);
    }
  };

  const updateGameStats = (game: any) => {
    const state = game.getMemoryState();
    setGameStats({
      matches: state.matches,
      attempts: state.attempts,
      time: game.getElapsedTime(),
      isComplete: state.matches === state.cards.length / 2,
    });
    setGameState(state);
  };

  const handleCardPress = (cardId: string) => {
    if (!gameInstance || !gameState) return;
    
    gameInstance.processPlayerAction({
      type: 'FLIP_CARD',
      payload: { cardId }
    });
    
    updateGameStats(gameInstance);
  };

  const resetGame = () => {
    if (gameInstance) {
      gameInstance.restart();
      setGameState(gameInstance.getMemoryState());
      setGameStats({
        matches: 0,
        attempts: 0,
        time: 0,
        isComplete: false,
      });
    }
  };

  const renderCard = (card: any, index: number) => {
    const cardSize = (screenWidth - 80) / gridSize;
    const isFlipped = card.isFlipped || card.isMatched;
    const isMatched = card.isMatched;
    
    return (
      <TouchableOpacity
        key={card.id}
        style={[
          styles.card,
          {
            width: cardSize - 8,
            height: cardSize - 8,
            backgroundColor: isMatched ? theme.matchedColor : 
                           isFlipped ? theme.cardColor : theme.primaryColor,
            borderColor: isMatched ? theme.matchedColor : theme.primaryColor,
          }
        ]}
        onPress={() => handleCardPress(card.id)}
        disabled={isFlipped || gameStats.isComplete}
        activeOpacity={0.8}
      >
        {isFlipped ? (
          <Text style={[styles.cardValue, { color: theme.textColor }]}>
            {card.value}
          </Text>
        ) : (
          <Text style={[styles.cardBack, { color: 'white' }]}>?</Text>
        )}
      </TouchableOpacity>
    );
  };

  const renderMemoryBoard = () => (
    <View style={styles.memoryBoard}>
      <View style={[styles.grid, { gridTemplateColumns: `repeat(${gridSize}, 1fr)` }]}>
        {gameState?.cards.map((card: any, index: number) => renderCard(card, index))}
      </View>
    </View>
  );

  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 ? 'טוען...' : 'התחל משחק'}
            </Text>
          </TouchableOpacity>
        </View>
        
        <View style={styles.gameInfo}>
          <Text style={[styles.infoText, { color: theme.textColor }]}>
            גודל רשת: {gridSize}x{gridSize}
          </Text>
          <Text style={[styles.infoText, { color: theme.textColor }]}>
            רמת קושי: {difficulty}
          </Text>
          {internalStats.totalGames > 0 && (
            <>
              <Text style={[styles.infoText, { color: theme.textColor }]}>
                משחקים קודמים: {internalStats.totalGames}
              </Text>
              <Text style={[styles.infoText, { color: theme.textColor }]}>
                ניקוד הטוב ביותר: {internalStats.bestScore}
              </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 }]}>משחק זיכרון</Text>
          {showStats && (
            <View style={styles.stats}>
              <Text style={[styles.statText, { color: theme.textColor }]}>
                זוגות: {gameStats.matches}
              </Text>
              <Text style={[styles.statText, { color: theme.textColor }]}>
                ניסיונות: {gameStats.attempts}
              </Text>
              <Text style={[styles.statText, { color: theme.textColor }]}>
                זמן: {Math.floor(gameStats.time / 1000)}s
              </Text>
            </View>
          )}
        </View>
        
        {renderMemoryBoard()}
        
        <View style={styles.controls}>
          {enableReset && (
            <TouchableOpacity
              style={[styles.controlButton, { backgroundColor: theme.secondaryColor }]}
              onPress={resetGame}
            >
              <Text style={styles.buttonText}>אפס משחק</Text>
            </TouchableOpacity>
          )}
          
          {showMenu && (
            <TouchableOpacity
              style={[styles.controlButton, { backgroundColor: theme.primaryColor }]}
              onPress={() => setCurrentScreen('menu')}
            >
              <Text style={styles.buttonText}>חזור לתפריט</Text>
            </TouchableOpacity>
          )}
        </View>
      </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: 28,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    marginBottom: 30,
    textAlign: 'center',
    opacity: 0.8,
  },
  menuButtons: {
    width: '100%',
    marginBottom: 30,
  },
  button: {
    padding: 15,
    borderRadius: 10,
    alignItems: 'center',
    marginVertical: 5,
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  gameInfo: {
    width: '100%',
  },
  infoText: {
    fontSize: 14,
    marginVertical: 2,
    textAlign: 'center',
  },
  gameContent: {
    flex: 1,
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  gameTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  stats: {
    alignItems: 'flex-end',
  },
  statText: {
    fontSize: 14,
    marginVertical: 2,
  },
  memoryBoard: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    alignItems: 'center',
  },
  card: {
    margin: 4,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 2,
  },
  cardValue: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  cardBack: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 20,
  },
  controlButton: {
    padding: 10,
    borderRadius: 8,
    minWidth: 100,
    alignItems: 'center',
  },
}); 