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

const { width: SCREEN_W } = Dimensions.get('window');
const AREA_SIZE = SCREEN_W - spacing.lg * 2;
const ROUNDS = 10;

export default function ReflexTap({ currentDay, onComplete }) {
  const difficulty = getDifficulty(currentDay);
  const targetSize = Math.max(50 - difficulty * 4, 34);
  const spawnDelay = Math.max(800 - difficulty * 100, 400);

  const [round, setRound] = useState(0);
  const [targetPos, setTargetPos] = useState(null);
  const [spawnTime, setSpawnTime] = useState(0);
  const [totalReaction, setTotalReaction] = useState(0);
  const [playing, setPlaying] = useState(false);

  const scale = useRef(new Animated.Value(0)).current;
  const glow = useRef(new Animated.Value(0.3)).current;
  const timerRef = useRef(null);

  const spawnTarget = useCallback(() => {
    const x = Math.random() * (AREA_SIZE - targetSize);
    const y = Math.random() * (AREA_SIZE - targetSize);
    setTargetPos({ x, y });
    setSpawnTime(Date.now());

    scale.setValue(0);
    glow.setValue(0.3);
    Animated.parallel([
      Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 20, bounciness: 10 }),
      Animated.loop(
        Animated.sequence([
          Animated.timing(glow, { toValue: 0.8, duration: 600, useNativeDriver: true }),
          Animated.timing(glow, { toValue: 0.3, duration: 600, useNativeDriver: true }),
        ])
      ),
    ]).start();
  }, [targetSize]);

  const start = () => {
    setRound(0);
    setTotalReaction(0);
    setPlaying(true);
  };

  useEffect(() => {
    if (playing && round < ROUNDS) {
      timerRef.current = setTimeout(spawnTarget, round === 0 ? 500 : spawnDelay);
    }
    if (playing && round >= ROUNDS) {
      setPlaying(false);
      setTargetPos(null);
      const avgMs = Math.round(totalReaction / ROUNDS);
      // Score: faster = higher. Max ~15 points for <200ms avg, min 1 for >1000ms
      const score = Math.max(1, Math.min(15, Math.round((1000 - avgMs) / 60)));
      onComplete(score, { avgReaction: avgMs, rounds: ROUNDS });
    }
    return () => clearTimeout(timerRef.current);
  }, [playing, round]);

  const handleTap = () => {
    if (!targetPos) return;
    const reaction = Date.now() - spawnTime;
    setTotalReaction((prev) => prev + reaction);
    setTargetPos(null);

    // Hit animation
    Animated.timing(scale, { toValue: 0, duration: 100, useNativeDriver: true }).start(() => {
      setRound((prev) => prev + 1);
    });
  };

  useEffect(() => { start(); }, []);

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.roundText}>{round} / {ROUNDS}</Text>
        {totalReaction > 0 && round > 0 && (
          <Text style={styles.avgText}>{Math.round(totalReaction / round)}ms avg</Text>
        )}
      </View>

      <View style={[styles.area, { width: AREA_SIZE, height: AREA_SIZE }]}>
        {!playing && round === 0 && (
          <Text style={styles.readyText}>Here we go...</Text>
        )}

        {targetPos && (
          <Pressable
            onPress={handleTap}
            style={[
              styles.targetHitbox,
              { left: targetPos.x, top: targetPos.y, width: targetSize * 1.5, height: targetSize * 1.5 },
            ]}
          >
            <Animated.View style={[styles.targetGlow, {
              width: targetSize * 1.8, height: targetSize * 1.8, borderRadius: targetSize * 0.9,
              opacity: glow, transform: [{ scale }],
            }]} />
            <Animated.View style={[styles.target, {
              width: targetSize, height: targetSize, borderRadius: targetSize / 2,
              transform: [{ scale }],
            }]}>
              <View style={[styles.targetCore, {
                width: targetSize * 0.5, height: targetSize * 0.5, borderRadius: targetSize * 0.25,
              }]} />
            </Animated.View>
          </Pressable>
        )}
      </View>

      <Text style={styles.hint}>Tap the glow — don't think, just react</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center' },
  header: { flexDirection: 'row', justifyContent: 'space-between', width: '100%', paddingHorizontal: spacing.md, marginBottom: spacing.md },
  roundText: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold },
  avgText: { color: colors.accent, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  area: {
    backgroundColor: 'rgba(19, 24, 49, 0.6)', borderRadius: borderRadius.lg,
    borderWidth: 1, borderColor: colors.border, overflow: 'hidden',
  },
  readyText: { color: colors.textMuted, fontSize: fonts.sizes.lg, position: 'absolute', top: '45%', alignSelf: 'center' },
  targetHitbox: { position: 'absolute', alignItems: 'center', justifyContent: 'center' },
  targetGlow: { position: 'absolute', backgroundColor: colors.accentGlow },
  target: { backgroundColor: 'rgba(0, 229, 255, 0.25)', alignItems: 'center', justifyContent: 'center' },
  targetCore: {
    backgroundColor: colors.accent,
    shadowColor: colors.accent, shadowOffset: { width: 0, height: 0 }, shadowOpacity: 1, shadowRadius: 12, elevation: 8,
  },
  hint: { color: colors.textMuted, fontSize: fonts.sizes.sm, marginTop: spacing.md },
});
