import React, { useRef, useEffect } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, Image, Animated, Easing, Platform } from 'react-native';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { LinearGradient } from 'expo-linear-gradient';

interface RewardModalProps {
  visible: boolean;
  onClose: () => void;
  rewardAmount: number;
}

export default function RewardModal({ visible, onClose, rewardAmount }: RewardModalProps) {
  const { claimReward } = useTradeStore();
  
  // Animation values
  const scaleAnim = useRef(new Animated.Value(0.5)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  const rotateAnim = useRef(new Animated.Value(0)).current;
  const pulseAnim = useRef(new Animated.Value(1)).current;
  const confettiAnim = useRef(new Animated.Value(0)).current;
  
  useEffect(() => {
    if (visible) {
      // Entrance animation
      Animated.parallel([
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 500,
          useNativeDriver: Platform.OS !== 'web',
          easing: Easing.out(Easing.back(1.7)),
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 400,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(confettiAnim, {
          toValue: 1,
          duration: 1000,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
      
      // Continuous rotation animation for the reward image
      Animated.loop(
        Animated.timing(rotateAnim, {
          toValue: 1,
          duration: 10000,
          useNativeDriver: Platform.OS !== 'web',
          easing: Easing.linear,
        })
      ).start();
      
      // Pulse animation for the claim button
      Animated.loop(
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.05,
            duration: 1000,
            useNativeDriver: Platform.OS !== 'web',
            easing: Easing.inOut(Easing.ease),
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 1000,
            useNativeDriver: Platform.OS !== 'web',
            easing: Easing.inOut(Easing.ease),
          }),
        ])
      ).start();
    } else {
      // Reset animation values when modal is hidden
      scaleAnim.setValue(0.5);
      opacityAnim.setValue(0);
      confettiAnim.setValue(0);
    }
  }, [visible]);
  
  // Convert rotation value to degrees for transform
  const rotate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });
  
  const handleClaim = () => {
    // Exit animation before closing
    Animated.parallel([
      Animated.timing(scaleAnim, {
        toValue: 1.2,
        duration: 300,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 300,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      claimReward(rewardAmount);
      onClose();
    });
  };
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={onClose}
    >
      <View style={styles.modalOverlay}>
        <Animated.View 
          style={[
            styles.modalContent,
            {
              opacity: opacityAnim,
              transform: [{ scale: scaleAnim }]
            }
          ]}
        >
          <LinearGradient
            colors={['rgba(243, 156, 18, 0.3)', 'rgba(52, 73, 94, 0.8)']}
            style={styles.modalGradient}
          />
          
          <Animated.View style={Platform.OS === 'web' ? {} : { transform: [{ rotate }] }}>
            <Image
              source={{ uri: 'https://cdn.prod.website-files.com/669543b2d7533930d1d7e753/6752e06fddf74c98d48df6d4_BAT%20COINS-%206.gif' }}
              style={styles.rewardImage}
            />
          </Animated.View>
          
          {Platform.OS !== 'web' && (
            <Animated.View 
              style={[
                styles.confettiContainer,
                { opacity: confettiAnim }
              ]}
            >
              {Array.from({ length: 20 }).map((_, i) => (
                <View 
                  key={i} 
                  style={[
                    styles.confetti,
                    {
                      left: `${Math.random() * 100}%`,
                      top: `${Math.random() * 100}%`,
                      backgroundColor: [colors.primary, colors.success, colors.accent, colors.error][Math.floor(Math.random() * 4)],
                      width: Math.random() * 8 + 2,
                      height: Math.random() * 8 + 2,
                      transform: [{ rotate: `${Math.random() * 360}deg` }]
                    }
                  ]} 
                />
              ))}
            </Animated.View>
          )}
          
          <Text style={styles.rewardText}>
            Awesome! Your trades have paid off with an exclusive gift! 🎁
          </Text>
          
          <Text style={styles.rewardAmount}>
            {rewardAmount.toLocaleString()} BATZ Coins
          </Text>
          
          <Animated.View style={Platform.OS === 'web' ? {} : { transform: [{ scale: pulseAnim }] }}>
            <TouchableOpacity 
              style={styles.claimButton} 
              onPress={handleClaim}
              activeOpacity={0.8}
            >
              <LinearGradient
                colors={['#F39C12', '#E67E22']}
                style={styles.buttonGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 0 }}
              />
              <Text style={styles.claimButtonText}>Claim Reward</Text>
            </TouchableOpacity>
          </Animated.View>
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  modalContent: {
    backgroundColor: colors.bgDark,
    borderRadius: 20,
    padding: 24,
    width: '90%',
    maxWidth: 350,
    alignItems: 'center',
    position: 'relative',
    overflow: 'hidden',
    shadowColor: colors.accent,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.5,
    shadowRadius: 20,
    elevation: 10,
  },
  modalGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  confettiContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    pointerEvents: 'none',
  },
  confetti: {
    position: 'absolute',
    width: 5,
    height: 5,
    borderRadius: 2,
  },
  rewardImage: {
    width: 140,
    height: 140,
    marginBottom: 20,
  },
  rewardText: {
    color: colors.textWhite,
    fontSize: 18,
    textAlign: 'center',
    marginBottom: 16,
    fontWeight: '600',
    lineHeight: 24,
  },
  rewardAmount: {
    color: colors.accent,
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 24,
    textShadowColor: 'rgba(243, 156, 18, 0.5)',
    textShadowOffset: { width: 0, height: 0 },
    textShadowRadius: 10,
  },
  claimButton: {
    borderRadius: 10,
    paddingVertical: 14,
    paddingHorizontal: 30,
    marginTop: 10,
    overflow: 'hidden',
    shadowColor: colors.accent,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.5,
    shadowRadius: 5,
    elevation: 5,
  },
  buttonGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  claimButtonText: {
    color: colors.bgBlack,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});