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

const TOTAL_ROUNDS = 5;

export default function FocusHold({ currentDay, onComplete }) {
  const difficulty = getDifficulty(currentDay);
  const holdDuration = 3000 + difficulty * 500; // 3.5s to 5s
  const circleSize = Math.max(120 - difficulty * 8, 88);

  const [round, setRound] = useState(0);
  const [holding, setHolding] = useState(false);
  const [failed, setFailed] = useState(false);
  const [successes, setSuccesses] = useState(0);
  const [message, setMessage] = useState('Hold it steady');

  const progress = useRef(new Animated.Value(0)).current;
  const ringOpacity = useRef(new Animated.Value(0.4)).current;
  const holdTimer = useRef(null);
  const animRef = useRef(null);

  const resetRound = useCallback(() => {
    progress.setValue(0);
    ringOpacity.setValue(0.4);
    setHolding(false);
    setFailed(false);
    setMessage('Hold it steady');
  }, []);

  useEffect(() => {
    if (round >= TOTAL_ROUNDS && round > 0) {
      const score = successes; // 0-5
      onComplete(score, { rounds: TOTAL_ROUNDS, successes });
    }
  }, [round]);

  const startHold = () => {
    if (round >= TOTAL_ROUNDS) return;
    setHolding(true);
    setFailed(false);
    setMessage('Stay with it...');

    animRef.current = Animated.timing(progress, {
      toValue: 1,
      duration: holdDuration,
      useNativeDriver: false,
    });

    Animated.timing(ringOpacity, { toValue: 1, duration: 300, useNativeDriver: true }).start();

    animRef.current.start(({ finished }) => {
      if (finished) {
        // Success
        setSuccesses((prev) => prev + 1);
        setMessage('Nailed it!');
        setHolding(false);
        setTimeout(() => {
          setRound((prev) => prev + 1);
          resetRound();
        }, 600);
      }
    });
  };

  const endHold = () => {
    if (!holding) return;
    // Released too early
    animRef.current?.stop();
    setHolding(false);
    setFailed(true);
    setMessage('You let go too soon');
    Animated.timing(ringOpacity, { toValue: 0.2, duration: 200, useNativeDriver: true }).start();

    setTimeout(() => {
      setRound((prev) => prev + 1);
      resetRound();
    }, 800);
  };

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: startHold,
      onPanResponderRelease: endHold,
      onPanResponderTerminate: endHold,
      onPanResponderMove: (_, gestureState) => {
        // Fail if finger moves too far
        const dist = Math.sqrt(gestureState.dx ** 2 + gestureState.dy ** 2);
        if (dist > circleSize * 0.6 && holding) {
          animRef.current?.stop();
          setHolding(false);
          setFailed(true);
          setMessage('Finger moved too far');
          Animated.timing(ringOpacity, { toValue: 0.2, duration: 200, useNativeDriver: true }).start();
          setTimeout(() => {
            setRound((prev) => prev + 1);
            resetRound();
          }, 800);
        }
      },
    })
  ).current;

  const fillWidth = progress.interpolate({
    inputRange: [0, 1],
    outputRange: ['0%', '100%'],
  });

  const ringColor = failed ? colors.error : holding ? colors.accent : colors.primary;

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.roundText}>{Math.min(round + 1, TOTAL_ROUNDS)} / {TOTAL_ROUNDS}</Text>
        <Text style={styles.successText}>{successes} held</Text>
      </View>

      <View style={styles.holdArea}>
        {/* Hold circle */}
        <View {...panResponder.panHandlers} style={styles.circleWrapper}>
          <Animated.View style={[styles.ring, {
            width: circleSize + 20, height: circleSize + 20, borderRadius: (circleSize + 20) / 2,
            borderColor: ringColor, opacity: ringOpacity,
          }]} />

          <View style={[styles.circle, {
            width: circleSize, height: circleSize, borderRadius: circleSize / 2,
          }]}>
            {/* Fill progress */}
            <Animated.View style={[styles.fill, {
              width: fillWidth, height: '100%', borderRadius: circleSize / 2,
              backgroundColor: failed ? 'rgba(255,82,82,0.3)' : 'rgba(0,229,255,0.3)',
            }]} />

            <Text style={styles.circleText}>
              {holding ? 'Holding...' : round >= TOTAL_ROUNDS ? 'Done' : 'Hold'}
            </Text>
          </View>
        </View>
      </View>

      <Text style={[styles.message, failed && styles.messageFail]}>{message}</Text>
      <Text style={styles.hint}>Press, hold, and stay perfectly still</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 },
  successText: { color: colors.success, fontSize: fonts.sizes.md, fontWeight: fonts.weights.medium },
  holdArea: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  circleWrapper: { alignItems: 'center', justifyContent: 'center' },
  ring: { position: 'absolute', borderWidth: 2, borderStyle: 'dashed' },
  circle: {
    backgroundColor: colors.surface, borderWidth: 2, borderColor: colors.border,
    alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
  },
  fill: { position: 'absolute', left: 0, top: 0 },
  circleText: { color: colors.text, fontSize: fonts.sizes.md, fontWeight: fonts.weights.semibold },
  message: { color: colors.accent, fontSize: fonts.sizes.lg, fontWeight: fonts.weights.semibold, marginBottom: spacing.sm },
  messageFail: { color: colors.error },
  hint: { color: colors.textMuted, fontSize: fonts.sizes.sm },
});
