import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Image, Dimensions } from 'react-native';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  withSpring,
  withDelay,
  withSequence,
  withRepeat,
  interpolate,
  Extrapolation,
  FadeIn,
  FadeInUp,
  FadeInDown,
  FadeOutLeft,
  SlideInRight,
  SlideOutLeft,
  Easing,
} from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii } from '../../theme/tokens';
import { H1, H2, Body, Button } from '../../components/ui';
import { t } from '../../i18n';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

interface WelcomeScreenProps {
  onGetStarted: () => void;
}

const SLIDES = [
  {
    icon: 'scale-outline' as const,
    titleKey: 'onboarding.slide1Title',
    descKey: 'onboarding.slide1Desc',
    color: colors.primary[500],
    gradientColors: [colors.primary[50], colors.primary[100]] as [string, string],
  },
  {
    icon: 'wallet-outline' as const,
    titleKey: 'onboarding.slide2Title',
    descKey: 'onboarding.slide2Desc',
    color: colors.secondary[500],
    gradientColors: [colors.secondary[50], colors.secondary[100]] as [string, string],
  },
  {
    icon: 'shield-checkmark-outline' as const,
    titleKey: 'onboarding.slide3Title',
    descKey: 'onboarding.slide3Desc',
    color: colors.brand.green,
    gradientColors: ['#E8F5E9', '#C8E6C9'] as [string, string],
  },
];

export function WelcomeScreen({ onGetStarted }: WelcomeScreenProps) {
  const [currentSlide, setCurrentSlide] = useState(0);

  // Logo animations
  const logoScale = useSharedValue(0);
  const logoRotate = useSharedValue(-15);
  const logoOpacity = useSharedValue(0);

  // Title animations
  const titleTranslateY = useSharedValue(30);
  const titleOpacity = useSharedValue(0);
  const subtitleTranslateY = useSharedValue(20);
  const subtitleOpacity = useSharedValue(0);

  // Icon pulse animation
  const iconPulse = useSharedValue(1);

  // Button animation
  const buttonTranslateY = useSharedValue(60);
  const buttonOpacity = useSharedValue(0);

  // Floating particles
  const float1 = useSharedValue(0);
  const float2 = useSharedValue(0);
  const float3 = useSharedValue(0);

  useEffect(() => {
    // Logo entrance: scale up with spring bounce + slight rotation
    logoOpacity.value = withDelay(200, withTiming(1, { duration: 600 }));
    logoScale.value = withDelay(200, withSpring(1, { damping: 8, stiffness: 100 }));
    logoRotate.value = withDelay(200, withSpring(0, { damping: 12, stiffness: 80 }));

    // Title staggered entrance
    titleOpacity.value = withDelay(700, withTiming(1, { duration: 600 }));
    titleTranslateY.value = withDelay(700, withSpring(0, { damping: 15, stiffness: 90 }));

    subtitleOpacity.value = withDelay(1000, withTiming(1, { duration: 600 }));
    subtitleTranslateY.value = withDelay(1000, withSpring(0, { damping: 15, stiffness: 90 }));

    // Button slide up
    buttonOpacity.value = withDelay(1400, withTiming(1, { duration: 500 }));
    buttonTranslateY.value = withDelay(1400, withSpring(0, { damping: 12, stiffness: 80 }));

    // Gentle icon pulse loop
    iconPulse.value = withDelay(
      1200,
      withRepeat(
        withSequence(
          withTiming(1.08, { duration: 1500, easing: Easing.inOut(Easing.ease) }),
          withTiming(1, { duration: 1500, easing: Easing.inOut(Easing.ease) })
        ),
        -1,
        true
      )
    );

    // Floating decorative elements
    float1.value = withRepeat(
      withSequence(
        withTiming(1, { duration: 3000, easing: Easing.inOut(Easing.ease) }),
        withTiming(0, { duration: 3000, easing: Easing.inOut(Easing.ease) })
      ),
      -1,
      true
    );
    float2.value = withDelay(
      1000,
      withRepeat(
        withSequence(
          withTiming(1, { duration: 4000, easing: Easing.inOut(Easing.ease) }),
          withTiming(0, { duration: 4000, easing: Easing.inOut(Easing.ease) })
        ),
        -1,
        true
      )
    );
    float3.value = withDelay(
      2000,
      withRepeat(
        withSequence(
          withTiming(1, { duration: 3500, easing: Easing.inOut(Easing.ease) }),
          withTiming(0, { duration: 3500, easing: Easing.inOut(Easing.ease) })
        ),
        -1,
        true
      )
    );
  }, []);

  const handleNext = () => {
    if (currentSlide < SLIDES.length - 1) {
      setCurrentSlide(currentSlide + 1);
    } else {
      onGetStarted();
    }
  };

  const slide = SLIDES[currentSlide];

  // Animated styles
  const logoAnimStyle = useAnimatedStyle(() => ({
    opacity: logoOpacity.value,
    transform: [
      { scale: logoScale.value },
      { rotate: `${logoRotate.value}deg` },
    ],
  }));

  const titleAnimStyle = useAnimatedStyle(() => ({
    opacity: titleOpacity.value,
    transform: [{ translateY: titleTranslateY.value }],
  }));

  const subtitleAnimStyle = useAnimatedStyle(() => ({
    opacity: subtitleOpacity.value,
    transform: [{ translateY: subtitleTranslateY.value }],
  }));

  const iconPulseStyle = useAnimatedStyle(() => ({
    transform: [{ scale: iconPulse.value }],
  }));

  const buttonAnimStyle = useAnimatedStyle(() => ({
    opacity: buttonOpacity.value,
    transform: [{ translateY: buttonTranslateY.value }],
  }));

  // Floating decorative circles
  const float1Style = useAnimatedStyle(() => ({
    transform: [
      { translateY: interpolate(float1.value, [0, 1], [0, -15], Extrapolation.CLAMP) },
      { translateX: interpolate(float1.value, [0, 1], [0, 8], Extrapolation.CLAMP) },
    ],
    opacity: interpolate(float1.value, [0, 0.5, 1], [0.3, 0.6, 0.3], Extrapolation.CLAMP),
  }));

  const float2Style = useAnimatedStyle(() => ({
    transform: [
      { translateY: interpolate(float2.value, [0, 1], [0, 12], Extrapolation.CLAMP) },
      { translateX: interpolate(float2.value, [0, 1], [0, -10], Extrapolation.CLAMP) },
    ],
    opacity: interpolate(float2.value, [0, 0.5, 1], [0.2, 0.5, 0.2], Extrapolation.CLAMP),
  }));

  const float3Style = useAnimatedStyle(() => ({
    transform: [
      { translateY: interpolate(float3.value, [0, 1], [0, -10], Extrapolation.CLAMP) },
      { translateX: interpolate(float3.value, [0, 1], [0, 6], Extrapolation.CLAMP) },
    ],
    opacity: interpolate(float3.value, [0, 0.5, 1], [0.25, 0.45, 0.25], Extrapolation.CLAMP),
  }));

  // Animated dots
  const renderDots = () => (
    <View style={styles.dotsRow}>
      {SLIDES.map((_, i) => {
        const isActive = i === currentSlide;
        return (
          <Animated.View
            key={i}
            style={[
              styles.dot,
              isActive && styles.dotActive,
            ]}
            layout={withSpring({ damping: 15, stiffness: 120 }) as any}
          />
        );
      })}
    </View>
  );

  return (
    <View style={styles.container}>
      {/* Floating decorative elements */}
      <Animated.View style={[styles.floatingCircle, styles.floatingCircle1, float1Style]} />
      <Animated.View style={[styles.floatingCircle, styles.floatingCircle2, float2Style]} />
      <Animated.View style={[styles.floatingCircle, styles.floatingCircle3, float3Style]} />

      {/* Logo with bounce entrance */}
      <Animated.View style={[styles.logoSection, logoAnimStyle]}>
        <View style={styles.logoGlow}>
          <Image
            source={require('../../../assets/branding/logo-wifaq.png')}
            style={styles.logo}
            resizeMode="contain"
          />
        </View>
      </Animated.View>

      {/* Title with staggered entrance */}
      <View style={styles.titleSection}>
        <Animated.View style={titleAnimStyle}>
          <H1 align="center" color={colors.neutral[900]}>
            {t('onboarding.welcomeTitle')}
          </H1>
        </Animated.View>
        <Animated.View style={subtitleAnimStyle}>
          <Body align="center" style={styles.subtitle}>
            {t('onboarding.welcomeSubtitle')}
          </Body>
        </Animated.View>
      </View>

      {/* Slide area with enhanced transitions */}
      <View style={styles.slideArea}>
        <Animated.View
          key={currentSlide}
          entering={SlideInRight.duration(400).springify().damping(18).stiffness(100)}
          exiting={SlideOutLeft.duration(300)}
          style={styles.slide}
        >
          {/* Animated icon with gradient background */}
          <Animated.View style={iconPulseStyle}>
            <LinearGradient
              colors={slide.gradientColors}
              style={styles.iconCircle}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
            >
              <Ionicons name={slide.icon} size={36} color={slide.color} />
            </LinearGradient>
          </Animated.View>

          <Animated.View entering={FadeInUp.delay(150).duration(350)}>
            <H2 align="center" style={styles.slideTitle}>
              {t(slide.titleKey)}
            </H2>
          </Animated.View>

          <Animated.View entering={FadeInUp.delay(250).duration(350)}>
            <Body align="center" style={styles.slideDesc}>
              {t(slide.descKey)}
            </Body>
          </Animated.View>
        </Animated.View>
      </View>

      {/* Animated dots */}
      {renderDots()}

      {/* Button with entrance animation */}
      <Animated.View style={[styles.footer, buttonAnimStyle]}>
        <Button
          title={
            currentSlide === SLIDES.length - 1
              ? t('onboarding.getStarted')
              : t('common.next')
          }
          onPress={handleNext}
          fullWidth
          size="lg"
        />
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
    overflow: 'hidden',
  },
  // Floating decorative circles
  floatingCircle: {
    position: 'absolute',
    borderRadius: 999,
  },
  floatingCircle1: {
    width: 120,
    height: 120,
    backgroundColor: colors.primary[100],
    top: 40,
    right: -30,
    opacity: 0.3,
  },
  floatingCircle2: {
    width: 80,
    height: 80,
    backgroundColor: colors.secondary[100],
    top: 180,
    left: -20,
    opacity: 0.2,
  },
  floatingCircle3: {
    width: 60,
    height: 60,
    backgroundColor: colors.brand.green + '30',
    bottom: 200,
    right: 20,
    opacity: 0.25,
  },
  logoSection: {
    alignItems: 'center',
    paddingTop: 60,
    paddingBottom: spacing.md,
  },
  logoGlow: {
    width: 100,
    height: 100,
    borderRadius: 50,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,255,255,0.9)',
    shadowColor: colors.primary[300],
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 12,
    elevation: 8,
  },
  logo: {
    width: 80,
    height: 80,
  },
  titleSection: {
    paddingHorizontal: spacing['3xl'],
    marginBottom: spacing.lg,
  },
  subtitle: {
    marginTop: spacing.sm,
    color: colors.neutral[500],
  },
  slideArea: {
    flex: 1,
    justifyContent: 'center',
  },
  slide: {
    paddingHorizontal: spacing['3xl'],
    alignItems: 'center',
    justifyContent: 'center',
  },
  iconCircle: {
    width: 80,
    height: 80,
    borderRadius: 40,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: spacing.xl,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  slideTitle: {
    marginBottom: spacing.sm,
  },
  slideDesc: {
    color: colors.neutral[500],
    maxWidth: 300,
    lineHeight: 22,
  },
  dotsRow: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: spacing.xl,
    gap: spacing.sm,
  },
  dot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: colors.neutral[200],
  },
  dotActive: {
    backgroundColor: colors.primary[500],
    width: 28,
    borderRadius: 14,
  },
  footer: {
    paddingHorizontal: spacing['2xl'],
    paddingBottom: 40,
  },
});
