import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, Animated, Pressable } from 'react-native';
import { colors, fonts, spacing, borderRadius } from '../../utils/theme';

const SCENARIOS = [
  {
    situation: "It's 6 AM. Your alarm rings. You're exhausted.",
    skip: 'Hit snooze and sleep in',
    cont: 'Get up. The old you would sleep.',
    correct: 'cont',
  },
  {
    situation: 'Your friends invite you out. You haven\'t done your habit yet.',
    skip: 'Go out. You\'ll do it tomorrow.',
    cont: 'Finish first. Identity comes first.',
    correct: 'cont',
  },
  {
    situation: "You failed yesterday. You feel like giving up.",
    skip: 'Take a break. Start again next week.',
    cont: 'One bad day doesn\'t erase progress.',
    correct: 'cont',
  },
  {
    situation: 'You\'re scrolling social media. 30 minutes have passed.',
    skip: 'Keep scrolling. You deserve a break.',
    cont: 'Close the app. Reclaim your time.',
    correct: 'cont',
  },
  {
    situation: 'Your workout is hard today. Everything hurts.',
    skip: 'Stop early. You did enough.',
    cont: 'Finish the set. Pain is temporary.',
    correct: 'cont',
  },
  {
    situation: "Nobody would know if you skipped today.",
    skip: 'Skip it. No one is watching.',
    cont: 'You would know. Do it for yourself.',
    correct: 'cont',
  },
  {
    situation: "You're tired after work. Your habit feels impossible.",
    skip: 'Rest tonight. Tomorrow will be better.',
    cont: 'Do even 5 minutes. Show up.',
    correct: 'cont',
  },
];

const ROUNDS = 5;

export default function TemptationChoice({ onComplete }) {
  const [round, setRound] = useState(0);
  const [score, setScore] = useState(0);
  const [feedback, setFeedback] = useState(null);
  const [scenarios] = useState(() => {
    // Shuffle and pick ROUNDS
    const shuffled = [...SCENARIOS].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, ROUNDS);
  });

  const fadeIn = useRef(new Animated.Value(0)).current;
  const feedbackScale = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (round < ROUNDS) {
      fadeIn.setValue(0);
      Animated.timing(fadeIn, { toValue: 1, duration: 400, useNativeDriver: true }).start();
    }
  }, [round]);

  useEffect(() => {
    if (round >= ROUNDS && round > 0) {
      onComplete(score, { rounds: ROUNDS, correct: score });
    }
  }, [round]);

  const handleChoice = (choice) => {
    if (feedback) return;
    const scenario = scenarios[round];
    const isCorrect = choice === scenario.correct;

    if (isCorrect) setScore((prev) => prev + 1);

    setFeedback({
      correct: isCorrect,
      message: isCorrect
        ? 'Your identity speaks louder than comfort.'
        : 'The old you made that choice. Choose again next time.',
    });

    feedbackScale.setValue(0);
    Animated.spring(feedbackScale, { toValue: 1, useNativeDriver: true, speed: 14, bounciness: 8 }).start();

    setTimeout(() => {
      setFeedback(null);
      setRound((prev) => prev + 1);
    }, 1800);
  };

  if (round >= ROUNDS) return null;

  const scenario = scenarios[round];

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.roundText}>{round + 1} / {ROUNDS}</Text>
        <Text style={styles.scoreText}>{score} correct</Text>
      </View>

      <Animated.View style={[styles.card, { opacity: fadeIn }]}>
        <Text style={styles.situation}>{scenario.situation}</Text>
      </Animated.View>

      {!feedback ? (
        <Animated.View style={[styles.choices, { opacity: fadeIn }]}>
          <Pressable
            style={[styles.choiceBtn, styles.skipBtn]}
            onPress={() => handleChoice('skip')}
          >
            <Text style={styles.choiceBtnText}>{scenario.skip}</Text>
          </Pressable>

          <Pressable
            style={[styles.choiceBtn, styles.contBtn]}
            onPress={() => handleChoice('cont')}
          >
            <Text style={styles.choiceBtnText}>{scenario.cont}</Text>
          </Pressable>
        </Animated.View>
      ) : (
        <Animated.View style={[styles.feedbackCard, { transform: [{ scale: feedbackScale }] }]}>
          <View style={[styles.feedbackDot, { backgroundColor: feedback.correct ? colors.success : colors.error }]} />
          <Text style={[styles.feedbackText, { color: feedback.correct ? colors.success : colors.error }]}>
            {feedback.correct ? 'Identity Aligned' : 'Temptation Won'}
          </Text>
          <Text style={styles.feedbackMessage}>{feedback.message}</Text>
        </Animated.View>
      )}

      <Text style={styles.hint}>What would the new you do?</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center' },
  header: { flexDirection: 'row', justifyContent: 'space-between', width: '100%', paddingHorizontal: spacing.md, marginBottom: spacing.xl },
  roundText: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold },
  scoreText: { color: colors.success, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  card: {
    backgroundColor: colors.surface, borderRadius: borderRadius.lg, padding: spacing.xl,
    borderWidth: 1, borderColor: colors.border, width: '100%', marginBottom: spacing.xl,
  },
  situation: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.semibold, lineHeight: 28, textAlign: 'center' },
  choices: { width: '100%', gap: spacing.md },
  choiceBtn: {
    paddingVertical: spacing.lg, paddingHorizontal: spacing.lg,
    borderRadius: borderRadius.md, borderWidth: 1.5,
  },
  skipBtn: { borderColor: 'rgba(255, 82, 82, 0.4)', backgroundColor: 'rgba(255, 82, 82, 0.06)' },
  contBtn: { borderColor: 'rgba(0, 230, 118, 0.4)', backgroundColor: 'rgba(0, 230, 118, 0.06)' },
  choiceBtnText: { color: colors.text, fontSize: fonts.sizes.md, textAlign: 'center', lineHeight: 22 },
  feedbackCard: {
    backgroundColor: colors.surface, borderRadius: borderRadius.lg, padding: spacing.xl,
    borderWidth: 1, borderColor: colors.border, width: '100%', alignItems: 'center',
  },
  feedbackDot: { width: 10, height: 10, borderRadius: 5, marginBottom: spacing.sm },
  feedbackText: { fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold, marginBottom: spacing.sm },
  feedbackMessage: { color: colors.textSecondary, fontSize: fonts.sizes.sm, textAlign: 'center', lineHeight: 20 },
  hint: { color: colors.textMuted, fontSize: fonts.sizes.sm, marginTop: 'auto', paddingBottom: spacing.md },
});
