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

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

export default function TimingTap({ currentDay, onComplete }) {
  const difficulty = getDifficulty(currentDay);
  const speed = 1200 - difficulty * 150;
  const zoneWidth = Math.max(ZONE_WIDTH_PCT - difficulty * 0.015, 0.08);

  const [round, setRound] = useState(0);
  const [results, setResults] = useState([]);
  const [lastResult, setLastResult] = useState(null);
  const [playing, setPlaying] = useState(true);
  const [waiting, setWaiting] = useState(false);

  const barPos = useRef(new Animated.Value(0)).current;
  const currentValue = useRef(0);
  const animRef = useRef(null);
  const resultScale = useRef(new Animated.Value(0)).current;

  const [zonePositions] = useState(() =>
    Array.from({ length: ROUNDS }, () => {
      const min = 0.1;
      const max = 0.9 - zoneWidth;
      return min + Math.random() * (max - min);
    })
  );

  // Track bar position in real time
  useEffect(() => {
    const id = barPos.addListener(({ value }) => {
      currentValue.current = value;
    });
    return () => barPos.removeListener(id);
  }, []);

  const startSweep = useCallback(() => {
    barPos.setValue(0);
    currentValue.current = 0;
    animRef.current = Animated.loop(
      Animated.sequence([
        Animated.timing(barPos, { toValue: 1, duration: speed, useNativeDriver: false }),
        Animated.timing(barPos, { toValue: 0, duration: speed, useNativeDriver: false }),
      ])
    );
    animRef.current.start();
  }, [speed]);

  useEffect(() => {
    if (playing && round < ROUNDS && !waiting) {
      startSweep();
    }
    return () => animRef.current?.stop();
  }, [round, playing, waiting]);

  useEffect(() => {
    if (round >= ROUNDS && results.length >= ROUNDS) {
      setPlaying(false);
      animRef.current?.stop();
      const perfects = results.filter((r) => r === 'perfect').length;
      const goods = results.filter((r) => r === 'good').length;
      const score = perfects * 2 + goods;
      onComplete(score, { perfects, goods, misses: ROUNDS - perfects - goods });
    }
  }, [results]);

  const handleTap = () => {
    if (!playing || round >= ROUNDS || waiting) return;

    // Stop animation and read current position
    animRef.current?.stop();
    setWaiting(true);

    const value = currentValue.current;
    const zone = zonePositions[round];
    const zoneCenter = zone + zoneWidth / 2;
    const distance = Math.abs(value - zoneCenter);

    let result;
    if (distance < zoneWidth * 0.3) result = 'perfect';
    else if (distance < zoneWidth * 0.8) result = 'good';
    else result = 'miss';

    setLastResult(result);
    setResults((prev) => [...prev, result]);

    resultScale.setValue(0);
    Animated.spring(resultScale, { toValue: 1, useNativeDriver: true, speed: 20, bounciness: 10 }).start();

    setTimeout(() => {
      setLastResult(null);
      setWaiting(false);
      setRound((prev) => prev + 1);
    }, 600);
  };

  const indicatorLeft = barPos.interpolate({
    inputRange: [0, 1],
    outputRange: [0, BAR_WIDTH - 4],
  });

  const currentZone = round < ROUNDS ? zonePositions[round] : 0.4;
  const resultColor = lastResult === 'perfect' ? colors.accent : lastResult === 'good' ? colors.success : colors.error;

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.roundText}>{Math.min(round + 1, ROUNDS)} / {ROUNDS}</Text>
        <View style={styles.resultsRow}>
          {results.map((r, i) => (
            <View
              key={i}
              style={[styles.resultDot, {
                backgroundColor: r === 'perfect' ? colors.accent : r === 'good' ? colors.success : colors.error,
              }]}
            />
          ))}
        </View>
      </View>

      <View style={styles.gameArea}>
        {/* Result flash */}
        {lastResult && (
          <Animated.View style={[styles.resultFlash, { transform: [{ scale: resultScale }] }]}>
            <Text style={[styles.resultText, { color: resultColor }]}>
              {lastResult.toUpperCase()}
            </Text>
          </Animated.View>
        )}

        {/* Timing bar */}
        <Pressable onPress={handleTap} style={styles.barContainer}>
          {/* Zone */}
          <View style={[styles.zone, {
            left: `${currentZone * 100}%`,
            width: `${zoneWidth * 100}%`,
          }]} />

          {/* Moving indicator */}
          <Animated.View style={[styles.indicator, { left: indicatorLeft }]} />

          {/* Bar background lines */}
          <View style={styles.barLine} />
        </Pressable>

        <Text style={styles.tapHint}>Tap at just the right moment</Text>
      </View>

      <Text style={styles.hint}>Find the rhythm. Hit the glow.</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center' },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%', paddingHorizontal: spacing.md, marginBottom: spacing.xl },
  roundText: { color: colors.text, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.bold },
  resultsRow: { flexDirection: 'row', gap: 4 },
  resultDot: { width: 8, height: 8, borderRadius: 4 },
  gameArea: { flex: 1, width: '100%', alignItems: 'center', justifyContent: 'center' },
  resultFlash: { position: 'absolute', top: '30%' },
  resultText: { fontSize: fonts.sizes.xxl, fontWeight: fonts.weights.bold, letterSpacing: 4 },
  barContainer: {
    width: BAR_WIDTH, height: 60,
    backgroundColor: colors.surface, borderRadius: borderRadius.md,
    borderWidth: 1, borderColor: colors.border,
    justifyContent: 'center', overflow: 'hidden',
  },
  barLine: {
    position: 'absolute', width: '100%', height: 2,
    backgroundColor: 'rgba(108, 99, 255, 0.15)', top: '50%',
  },
  zone: {
    position: 'absolute', height: '100%',
    backgroundColor: 'rgba(0, 229, 255, 0.12)',
    borderLeftWidth: 2, borderRightWidth: 2, borderColor: 'rgba(0, 229, 255, 0.4)',
  },
  indicator: {
    position: 'absolute', width: 4, height: '100%',
    backgroundColor: colors.text, borderRadius: 2,
    shadowColor: colors.text, shadowOffset: { width: 0, height: 0 }, shadowOpacity: 0.8, shadowRadius: 6,
  },
  tapHint: { color: colors.textMuted, fontSize: fonts.sizes.sm, marginTop: spacing.lg },
  hint: { color: colors.textMuted, fontSize: fonts.sizes.sm, marginTop: 'auto', paddingBottom: spacing.md },
});
