import React, { useRef, useState, useEffect, useCallback } from 'react';
import {
  View, Text, Image, StyleSheet, FlatList,
  Dimensions, TouchableOpacity, Animated,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import StarField from '../components/StarField';
import Button from '../components/Button';
import useAuthStore from '../store/useAuthStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const { width, height } = Dimensions.get('window');
const ONBOARDING_KEY = 'onboarding_done';

const pages = [
  {
    id: '1',
    iconSize: 90,
    glowIntensity: 0.4,
    headline: 'Become\nsomeone new',
    body: 'Nova40 is a 40-day journey that helps you\ntransform your identity through daily habits,\njournaling, and real self-reflection.',
    accent: colors.primary,
  },
  {
    id: '2',
    iconSize: 90,

    glowIntensity: 0.6,
    headline: 'Your story.\nYour plan.\nYour growth.',
    body: null,
    accent: colors.accent,
    bullets: [
      'Write your story — AI builds your personal path',
      'Track habits and mood every single day',
      'Train your mind with focus challenges',
      'Watch yourself grow on a 40-day map',
    ],
  },
  {
    id: '3',
    iconSize: 90,
    glowIntensity: 1,
    showOrbit: true,
    headline: '40 days is\nall it takes.',
    body: "You don't need to be perfect.\nJust show up — one day at a time.\nThat's the whole secret.",
    accent: colors.success,
    isLast: true,
  },
];

function PageContent({ item, isActive }) {
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(40)).current;
  const iconFade = useRef(new Animated.Value(0)).current;
  const iconScale = useRef(new Animated.Value(0.8)).current;
  const pulse = useRef(new Animated.Value(1)).current;

  useEffect(() => {
    if (isActive) {
      iconFade.setValue(0);
      iconScale.setValue(0.8);
      fadeAnim.setValue(0);
      slideAnim.setValue(40);
      Animated.sequence([
        Animated.parallel([
          Animated.timing(iconFade, { toValue: 1, duration: 600, useNativeDriver: true }),
          Animated.spring(iconScale, { toValue: 1, useNativeDriver: true, speed: 12, bounciness: 6 }),
        ]),
        Animated.parallel([
          Animated.timing(fadeAnim, { toValue: 1, duration: 500, useNativeDriver: true }),
          Animated.timing(slideAnim, { toValue: 0, duration: 500, useNativeDriver: true }),
        ]),
      ]).start();
    }
  }, [isActive]);

  useEffect(() => {
    const anim = Animated.loop(
      Animated.sequence([
        Animated.timing(pulse, { toValue: 1.1, duration: 2500, useNativeDriver: true }),
        Animated.timing(pulse, { toValue: 1, duration: 2500, useNativeDriver: true }),
      ])
    );
    anim.start();
    return () => anim.stop();
  }, []);

  return (
    <View style={styles.page}>
      {/* Logo */}
      <Animated.View style={[styles.iconArea, { opacity: iconFade, transform: [{ scale: iconScale }] }]}>
        <Animated.View
          style={[
            styles.glow,
            {
              width: item.iconSize * 2.4, height: item.iconSize * 2.4,
              borderRadius: item.iconSize * 1.2, opacity: item.glowIntensity * 0.35,
              transform: [{ scale: pulse }],
            },
          ]}
        />
        {item.showOrbit && (
          <View style={[styles.orbit, {
            width: item.iconSize * 2.8, height: item.iconSize * 2.8,
            borderRadius: item.iconSize * 1.4,
          }]} />
        )}
        <Image
          source={require('../../assets/icon.png')}
          style={{ width: item.iconSize, height: item.iconSize }}
          resizeMode="contain"
        />
      </Animated.View>

      {/* Content */}
      <Animated.View style={[styles.textArea, { opacity: fadeAnim, transform: [{ translateY: slideAnim }] }]}>
        {/* Accent line */}
        <View style={[styles.accentLine, { backgroundColor: item.accent }]} />

        <Text style={styles.headline}>{item.headline}</Text>

        {item.body && (
          <Text style={styles.body}>{item.body}</Text>
        )}

        {item.bullets && (
          <View style={styles.bulletList}>
            {item.bullets.map((text, i) => (
              <View key={i} style={styles.bulletRow}>
                <View style={[styles.bulletDot, { backgroundColor: item.accent }]} />
                <Text style={styles.bulletText}>{text}</Text>
              </View>
            ))}
          </View>
        )}
      </Animated.View>
    </View>
  );
}

export default function OnboardingScreen({ navigation }) {
  const flatListRef = useRef(null);
  const [currentIndex, setCurrentIndex] = useState(0);
  const buttonFade = useRef(new Animated.Value(0)).current;
  const buttonSlide = useRef(new Animated.Value(20)).current;

  const isLastPage = currentIndex === pages.length - 1;

  useEffect(() => {
    if (isLastPage) {
      Animated.parallel([
        Animated.timing(buttonFade, { toValue: 1, duration: 500, delay: 300, useNativeDriver: true }),
        Animated.timing(buttonSlide, { toValue: 0, duration: 500, delay: 300, useNativeDriver: true }),
      ]).start();
    } else {
      buttonFade.setValue(0);
      buttonSlide.setValue(20);
    }
  }, [isLastPage]);

  const completeOnboarding = useCallback(async () => {
    await AsyncStorage.setItem(ONBOARDING_KEY, 'true');
    const session = useAuthStore.getState().session;
    if (session) {
      navigation.reset({ index: 0, routes: [{ name: 'IdentityStory' }] });
    } else {
      navigation.reset({ index: 0, routes: [{ name: 'Login' }] });
    }
  }, [navigation]);

  const onViewableItemsChanged = useRef(({ viewableItems }) => {
    if (viewableItems.length > 0) {
      setCurrentIndex(viewableItems[0].index ?? 0);
    }
  }).current;

  return (
    <View style={styles.container}>
      <StarField count={35} />

      {/* Skip */}
      {!isLastPage && (
        <TouchableOpacity style={styles.skip} onPress={completeOnboarding}>
          <Text style={styles.skipText}>Skip</Text>
        </TouchableOpacity>
      )}

      <FlatList
        ref={flatListRef}
        data={pages}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        keyExtractor={(item) => item.id}
        onViewableItemsChanged={onViewableItemsChanged}
        viewabilityConfig={{ viewAreaCoveragePercentThreshold: 50 }}
        renderItem={({ item, index }) => (
          <PageContent item={item} isActive={index === currentIndex} />
        )}
      />

      {/* Bottom */}
      <View style={styles.bottom}>
        {isLastPage && (
          <Animated.View style={[styles.ctaWrapper, { opacity: buttonFade, transform: [{ translateY: buttonSlide }] }]}>
            <Button title="Let's Begin" onPress={completeOnboarding} />
          </Animated.View>
        )}

        {/* Dots */}
        <View style={styles.indicators}>
          {pages.map((_, i) => (
            <Animated.View
              key={i}
              style={[
                styles.dot,
                currentIndex === i && [styles.dotActive, { backgroundColor: pages[currentIndex].accent }],
              ]}
            />
          ))}
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  skip: {
    position: 'absolute',
    top: 58,
    right: 24,
    zIndex: 10,
    paddingVertical: spacing.sm,
    paddingHorizontal: spacing.md,
    borderRadius: borderRadius.full,
    backgroundColor: 'rgba(255,255,255,0.06)',
  },
  skipText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.medium,
  },
  page: {
    width,
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing.xl,
    paddingBottom: 130,
  },

  // Logo
  iconArea: {
    alignItems: 'center',
    justifyContent: 'center',
    alignSelf: 'center',
    width: 280,
    height: 220,
    marginBottom: spacing.xl,
  },
  glow: {
    backgroundColor: colors.planetGlow,
    position: 'absolute',
  },
  orbit: {
    borderWidth: 1.5,
    borderColor: colors.orbitLine,
    borderStyle: 'dashed',
    position: 'absolute',
  },

  // Text
  textArea: {
    alignItems: 'center',
    paddingHorizontal: spacing.xs,
  },
  accentLine: {
    width: 32,
    height: 3,
    borderRadius: 2,
    marginBottom: spacing.lg,
  },
  headline: {
    color: colors.text,
    fontSize: 30,
    fontWeight: fonts.weights.bold,
    lineHeight: 40,
    marginBottom: spacing.lg,
    letterSpacing: -0.5,
    textAlign: 'center',
  },
  body: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 26,
    textAlign: 'center',
  },

  // Bullets
  bulletList: {
    marginTop: spacing.xs,
    alignItems: 'center',
  },
  bulletRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: spacing.md,
    maxWidth: 300,
  },
  bulletDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    marginTop: 8,
    marginRight: spacing.md,
  },
  bulletText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 24,
    flex: 1,
  },

  // Bottom
  bottom: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing.xl + 10,
    paddingTop: spacing.md,
  },
  ctaWrapper: {
    marginBottom: spacing.lg,
  },
  indicators: {
    flexDirection: 'row',
    justifyContent: 'center',
    gap: spacing.sm,
  },
  dot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: 'rgba(255,255,255,0.15)',
  },
  dotActive: {
    width: 28,
  },
});
