import React, { useEffect, useState, useRef, useCallback } from 'react';
import { View, Text, StyleSheet, Animated, Dimensions } from 'react-native';
import { CommonActions, useFocusEffect } from '@react-navigation/native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import OrbitContainer from '../components/OrbitContainer';
import Button from '../components/Button';
import useIdentityStore from '../store/useIdentityStore';
import { colors, fonts, spacing } from '../utils/theme';
import { getDayPhase, isCriticalDay } from '../utils/helpers';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const ORBIT_SIZE = Math.min(SCREEN_WIDTH * 0.82, 340);
const PLANET_SIZE = ORBIT_SIZE * 0.28;

export default function HomeScreen({ navigation }) {
  const identity = useIdentityStore((s) => s.identity);
  const currentDay = useIdentityStore((s) => s.currentDay);
  const loadIdentity = useIdentityStore((s) => s.fetchIdentity);
  const [loading, setLoading] = useState(true);

  // Entrance animations
  const fadeHeader = useRef(new Animated.Value(0)).current;
  const fadeOrbit = useRef(new Animated.Value(0)).current;
  const scaleOrbit = useRef(new Animated.Value(0.85)).current;
  const fadeBottom = useRef(new Animated.Value(0)).current;
  const slideBottom = useRef(new Animated.Value(30)).current;

  useFocusEffect(
    useCallback(() => {
      let active = true;
      const init = async () => {
        await loadIdentity();
        if (active) setLoading(false);
      };
      init();
      return () => { active = false; };
    }, [])
  );

  useEffect(() => {
    if (!loading && !identity) {
      navigation.dispatch(
        CommonActions.reset({ index: 0, routes: [{ name: 'IdentityStory' }] })
      );
    }
    if (!loading && identity) {
      Animated.stagger(150, [
        Animated.timing(fadeHeader, { toValue: 1, duration: 600, useNativeDriver: true }),
        Animated.parallel([
          Animated.timing(fadeOrbit, { toValue: 1, duration: 800, useNativeDriver: true }),
          Animated.spring(scaleOrbit, { toValue: 1, useNativeDriver: true, speed: 8, bounciness: 6 }),
        ]),
        Animated.parallel([
          Animated.timing(fadeBottom, { toValue: 1, duration: 500, useNativeDriver: true }),
          Animated.timing(slideBottom, { toValue: 0, duration: 500, useNativeDriver: true }),
        ]),
      ]).start();
    }
  }, [loading, identity]);

  useEffect(() => {
    if (identity && currentDay > 0 && isCriticalDay(currentDay)) {
      showAlert(
        'Important Day',
        `Day ${currentDay} is one of the toughest. Many people quit here — but not you. Want to train your focus?`,
        [
          { text: 'Later', style: 'cancel' },
          { text: 'Take Challenge', onPress: () => navigation.navigate('Game') },
        ]
      );
    }
  }, [currentDay]);

  const handleDotPress = useCallback((_dayIndex, status) => {
    if (status === 'current') {
      navigation.navigate('Daily');
    }
    // Future: show past day summary for completed dots
  }, [navigation]);

  if (loading || !identity) {
    return (
      <ScreenWrapper>
        <View style={styles.loadingContainer}>
          <Text style={styles.loadingText}>Getting things ready...</Text>
        </View>
      </ScreenWrapper>
    );
  }

  if (currentDay > 40) {
    navigation.dispatch(
      CommonActions.reset({ index: 0, routes: [{ name: 'Completion' }] })
    );
    return null;
  }

  const phase = getDayPhase(currentDay);
  const glowIntensity = 0.3 + (currentDay / 40) * 0.7;
  const progress = ((currentDay - 1) / 40) * 100;

  return (
    <ScreenWrapper>
      <View style={styles.container}>
        {/* Phase & Identity Header */}
        <Animated.View style={[styles.header, { opacity: fadeHeader }]}>
          <Text style={styles.phase}>{phase.toUpperCase()} PHASE</Text>
          <Text style={styles.identity} numberOfLines={2}>{identity.title}</Text>
        </Animated.View>

        {/* Orbit System */}
        <Animated.View
          style={[
            styles.orbitArea,
            { opacity: fadeOrbit, transform: [{ scale: scaleOrbit }] },
          ]}
        >
          <OrbitContainer
            size={ORBIT_SIZE}
            currentDay={currentDay}
            planetSize={PLANET_SIZE}
            glowIntensity={glowIntensity}
            onDotPress={handleDotPress}
          />
        </Animated.View>

        {/* Bottom Info */}
        <Animated.View
          style={[
            styles.bottomSection,
            { opacity: fadeBottom, transform: [{ translateY: slideBottom }] },
          ]}
        >
          {/* Day Counter */}
          <View style={styles.dayRow}>
            <Text style={styles.dayNumber}>Day {currentDay}</Text>
            <Text style={styles.dayTotal}> of 40</Text>
          </View>

          {/* Progress Bar */}
          <View style={styles.progressBar}>
            <View style={[styles.progressFill, { width: `${progress}%` }]}>
              <View style={styles.progressGlow} />
            </View>
          </View>

          {/* Critical Day Badge */}
          {isCriticalDay(currentDay) && (
            <View style={styles.criticalBadge}>
              <View style={styles.criticalDot} />
              <Text style={styles.criticalText}>This is a turning point. Stay with it.</Text>
            </View>
          )}

          {/* Start Button */}
          <Button
            title="Let's Do This"
            onPress={() => navigation.navigate('Daily')}
            style={styles.startButton}
          />
        </Animated.View>
      </View>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: spacing.lg,
    paddingBottom: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
  },

  // Header
  header: {
    alignItems: 'center',
    paddingTop: spacing.sm,
  },
  phase: {
    color: colors.accent,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 4,
    marginBottom: spacing.xs,
  },
  identity: {
    color: colors.text,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.semibold,
    textAlign: 'center',
    lineHeight: 28,
  },

  // Orbit
  orbitArea: {
    alignItems: 'center',
    justifyContent: 'center',
  },

  // Bottom
  bottomSection: {
    width: '100%',
    alignItems: 'center',
  },
  dayRow: {
    flexDirection: 'row',
    alignItems: 'baseline',
    marginBottom: spacing.md,
  },
  dayNumber: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
  },
  dayTotal: {
    color: colors.textMuted,
    fontSize: fonts.sizes.lg,
    fontWeight: fonts.weights.medium,
  },

  // Progress
  progressBar: {
    width: '100%',
    height: 4,
    backgroundColor: colors.surface,
    borderRadius: 2,
    marginBottom: spacing.lg,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    backgroundColor: colors.primary,
    borderRadius: 2,
    position: 'relative',
  },
  progressGlow: {
    position: 'absolute',
    right: 0,
    top: -2,
    width: 16,
    height: 8,
    borderRadius: 4,
    backgroundColor: colors.primaryLight,
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 1,
    shadowRadius: 6,
    elevation: 4,
  },

  // Critical
  criticalBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 82, 82, 0.1)',
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: 'rgba(255, 82, 82, 0.3)',
    marginBottom: spacing.md,
  },
  criticalDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: colors.error,
    marginRight: spacing.sm,
  },
  criticalText: {
    color: colors.error,
    fontSize: fonts.sizes.xs,
    fontWeight: fonts.weights.bold,
    letterSpacing: 1,
  },

  // Button
  startButton: {
    width: '100%',
  },
});
