import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet, Pressable, Animated, ScrollView } from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
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 } from '../services/gameService';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const GAMES = [
  {
    id: 'reflex_tap',
    name: 'Reflex Tap',
    icon: '⚡',
    desc: 'Train quick action',
    stat: 'Discipline',
    color: colors.accent,
  },
  {
    id: 'focus_hold',
    name: 'Focus Hold',
    icon: '🎯',
    desc: 'Train focus & stability',
    stat: 'Focus',
    color: colors.primary,
  },
  {
    id: 'temptation_choice',
    name: 'Temptation',
    icon: '🧠',
    desc: 'Real-life decisions',
    stat: 'Consistency',
    color: colors.success,
  },
  {
    id: 'timing_tap',
    name: 'Timing Tap',
    icon: '⏱',
    desc: 'Precision & awareness',
    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 [saving, setSaving] = useState(false);

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

  const handleGameComplete = useCallback((score, details) => {
    setResult({ score, details });
    setPhase('result');
  }, []);

  const handleSave = async () => {
    if (!identity || !result) return;
    setSaving(true);
    try {
      await saveGameSession(identity.id, activeGame, result.score);
      navigation.goBack();
    } catch (e) {
      showAlert('Error', 'Failed to save score.');
    } finally {
      setSaving(false);
    }
  };

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

  // === SELECT PHASE ===
  if (phase === 'select') {
    return (
      <ScreenWrapper>
        <View style={styles.selectContainer}>
          <Text style={styles.selectTitle}>Mind Training</Text>
          <Text style={styles.selectSubtitle}>Choose your challenge</Text>

          <ScrollView contentContainerStyle={styles.gameGrid} showsVerticalScrollIndicator={false}>
            {GAMES.map((game) => (
              <Pressable
                key={game.id}
                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>
                <View style={[styles.statBadge, { borderColor: game.color }]}>
                  <Text style={[styles.statBadgeText, { color: game.color }]}>+{game.stat}</Text>
                </View>
              </Pressable>
            ))}
          </ScrollView>
        </View>
      </ScreenWrapper>
    );
  }

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

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

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

  return (
    <ScreenWrapper>
      <View style={styles.playContainer}>
        <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',
    gap: spacing.md,
    paddingBottom: spacing.xxl,
  },
  gameCard: {
    width: '47%',
    backgroundColor: colors.surface,
    borderRadius: borderRadius.lg,
    padding: spacing.lg,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
  },
  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.md,
  },
  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.lg,
  },
});
