import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet, Pressable, ScrollView } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import FadeIn from '../components/FadeIn';
import NovaAd from '../components/NovaAd';
import ReflexTap from '../components/games/ReflexTap';
import FocusHold from '../components/games/FocusHold';
import TemptationChoice from '../components/games/TemptationChoice';
import TimingTap from '../components/games/TimingTap';
import GameResult from '../components/games/GameResult';
import useIdentityStore from '../store/useIdentityStore';
import { saveGameSession, getGameScores } from '../services/gameService';
import { trackGamePlayed, logScreenView } from '../services/analytics';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const GAMES = [
  {
    id: 'reflex_tap',
    name: 'Reflex Tap',
    icon: '⚡',
    desc: 'Sharpen your reflexes',
    stat: 'Discipline',
    color: colors.accent,
  },
  {
    id: 'focus_hold',
    name: 'Focus Hold',
    icon: '🎯',
    desc: 'Practice being still',
    stat: 'Focus',
    color: colors.primary,
  },
  {
    id: 'temptation_choice',
    name: 'Temptation',
    icon: '🧠',
    desc: 'Face real temptations',
    stat: 'Consistency',
    color: colors.success,
  },
  {
    id: 'timing_tap',
    name: 'Timing Tap',
    icon: '⏱',
    desc: 'Find your rhythm',
    stat: 'Focus',
    color: colors.warning,
  },
];

// Phase: 'select' | 'playing' | 'result'
export default function MiniGameScreen({ navigation, route }) {
  const currentDay = useIdentityStore((s) => s.currentDay);
  const identity = useIdentityStore((s) => s.identity);

  const [phase, setPhase] = useState(route?.params?.gameType ? 'playing' : 'select');
  const [activeGame, setActiveGame] = useState(route?.params?.gameType || null);
  const [result, setResult] = useState(null);
  const [focusCount, setFocusCount] = useState(0);
  const [gameScores, setGameScores] = useState({});

  useFocusEffect(
    useCallback(() => {
      setFocusCount((c) => c + 1);
      if (identity?.id) {
        getGameScores(identity.id).then(setGameScores);
      }
    }, [identity?.id])
  );

  const selectGame = (gameId) => {
    setActiveGame(gameId);
    setPhase('playing');
    setResult(null);
  };

  const handleGameComplete = useCallback(async (score, details) => {
    setResult({ score, details });
    setPhase('result');
    trackGamePlayed(activeGame, score);

    // Auto-save score immediately
    if (identity?.id && activeGame) {
      try {
        await saveGameSession(identity.id, activeGame, score);
        const updated = await getGameScores(identity.id);
        setGameScores(updated);
      } catch (_) {}
    }
  }, [identity?.id, activeGame]);

  const handleExit = () => {
    setPhase('select');
    setActiveGame(null);
    setResult(null);
  };

  const handleRetry = () => {
    setResult(null);
    setPhase('playing');
  };

  // === SELECT PHASE ===
  if (phase === 'select') {
    return (
      <ScreenWrapper>
        <View style={styles.selectContainer}>
          <FadeIn delay={0} trigger={focusCount}>
            <Text style={styles.selectTitle}>Train Your Mind</Text>
            <Text style={styles.selectSubtitle}>Pick a quick challenge</Text>
          </FadeIn>

          <ScrollView contentContainerStyle={styles.gameGrid} showsVerticalScrollIndicator={false}>
            {GAMES.map((game, i) => (
              <FadeIn key={game.id} delay={100 + i * 80} trigger={focusCount} style={styles.gameCardWrap}>
                <Pressable
                  style={({ pressed }) => [styles.gameCard, pressed && styles.gameCardPressed]}
                  onPress={() => selectGame(game.id)}
                >
                  <Text style={styles.gameIcon}>{game.icon}</Text>
                  <Text style={styles.gameName}>{game.name}</Text>
                  <Text style={styles.gameDesc}>{game.desc}</Text>
                  {gameScores[game.id] && (
                    <View style={styles.scoreRow}>
                      <Text style={styles.scoreLast}>Last: {gameScores[game.id].last}</Text>
                      <Text style={[styles.scoreBest, { color: game.color }]}>Best: {gameScores[game.id].best}</Text>
                    </View>
                  )}
                  <View style={[styles.statBadge, { borderColor: game.color }]}>
                    <Text style={[styles.statBadgeText, { color: game.color }]}>+{game.stat}</Text>
                  </View>
                </Pressable>
              </FadeIn>
            ))}
          </ScrollView>
          <NovaAd />
        </View>
      </ScreenWrapper>
    );
  }

  // === RESULT PHASE ===
  if (phase === 'result' && result) {
    return (
      <ScreenWrapper>
        <GameResult
          gameType={activeGame}
          score={result.score}
          details={result.details}
          onExit={handleExit}
          onRetry={handleRetry}
        />
      </ScreenWrapper>
    );
  }

  // === PLAYING PHASE ===
  const GameComponent = {
    reflex_tap: ReflexTap,
    focus_hold: FocusHold,
    temptation_choice: TemptationChoice,
    timing_tap: TimingTap,
  }[activeGame];

  if (!GameComponent) {
    setPhase('select');
    return null;
  }

  const gameName = GAMES.find((g) => g.id === activeGame)?.name || 'Game';

  return (
    <ScreenWrapper>
      <View style={styles.playContainer}>
        {/* Exit header */}
        <View style={styles.playHeader}>
          <Pressable style={({ pressed }) => [styles.exitBtn, pressed && styles.exitBtnPressed]} onPress={handleExit}>
            <View style={styles.exitIconWrap}>
              <Text style={styles.exitIcon}>{'\u2715'}</Text>
            </View>
          </Pressable>
          <View style={styles.playTitleWrap}>
            <Text style={styles.playTitleEmoji}>{GAMES.find((g) => g.id === activeGame)?.icon || '🎮'}</Text>
            <Text style={styles.playTitle}>{gameName}</Text>
          </View>
          <View style={styles.exitPlaceholder} />
        </View>
        <GameComponent
          currentDay={currentDay}
          onComplete={handleGameComplete}
        />
      </View>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  // Select
  selectContainer: {
    flex: 1,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.xl,
  },
  selectTitle: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.xs,
  },
  selectSubtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    marginBottom: spacing.xl,
  },
  gameGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    paddingBottom: spacing.xxl,
  },
  gameCardWrap: {
    width: '48%',
    marginBottom: spacing.md,
  },
  gameCard: {
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
    height: 160,
  },
  gameCardPressed: {
    opacity: 0.7,
    transform: [{ scale: 0.97 }],
  },
  gameIcon: {
    fontSize: 32,
    marginBottom: spacing.sm,
  },
  gameName: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.semibold,
    marginBottom: spacing.xs,
  },
  gameDesc: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.xs,
    textAlign: 'center',
    marginBottom: spacing.sm,
  },
  scoreRow: {
    flexDirection: 'row',
    gap: spacing.sm,
    marginBottom: spacing.sm,
  },
  scoreLast: {
    color: colors.textMuted,
    fontSize: 10,
    fontWeight: fonts.weights.medium,
  },
  scoreBest: {
    fontSize: 10,
    fontWeight: fonts.weights.bold,
  },
  statBadge: {
    borderWidth: 1,
    borderRadius: borderRadius.full,
    paddingHorizontal: spacing.sm,
    paddingVertical: 2,
  },
  statBadgeText: {
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.semibold,
  },

  // Playing
  playContainer: {
    flex: 1,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.sm,
  },
  playHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: spacing.md,
  },
  exitBtn: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(255,82,82,0.1)',
    borderWidth: 1,
    borderColor: 'rgba(255,82,82,0.25)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  exitBtnPressed: {
    backgroundColor: 'rgba(255,82,82,0.25)',
    transform: [{ scale: 0.92 }],
  },
  exitIconWrap: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  exitIcon: {
    color: colors.error,
    fontSize: 14,
    fontWeight: fonts.weights.bold,
  },
  playTitleWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
  },
  playTitleEmoji: {
    fontSize: 16,
  },
  playTitle: {
    color: colors.text,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },
  exitPlaceholder: {
    width: 36,
  },
});
