import React, { useRef, useEffect } from 'react';
import { StyleSheet, View, TouchableOpacity, Animated, Vibration, Platform } from 'react-native';
import { Bell } from 'lucide-react-native';
import { useTheme } from '@/context/ThemeContext';

interface NotificationBadgeProps {
  hasNewMessages: boolean;
  onPress: () => void;
}

export default function NotificationBadge({ hasNewMessages, onPress }: NotificationBadgeProps) {
  const { colors } = useTheme();
  
  // Animation for the badge
  const pulseAnim = useRef(new Animated.Value(1)).current;
  const scaleAnim = useRef(new Animated.Value(1)).current;
  
  // Create pulsing animation for the badge when there are new messages
  useEffect(() => {
    if (hasNewMessages) {
      const createPulseAnimation = () => {
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.3,
            duration: 500,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 500,
            useNativeDriver: true,
          }),
        ]).start(() => {
          // Repeat the animation
          createPulseAnimation();
        });
      };
      
      createPulseAnimation();
      
      return () => {
        pulseAnim.stopAnimation();
      };
    }
  }, [hasNewMessages]);
  
  const handlePress = () => {
    // Provide haptic feedback on native platforms
    if (Platform.OS !== 'web') {
      try {
        Vibration.vibrate(10);
      } catch (error) {
        console.error("Vibration error:", error);
      }
    }
    
    // Animate button press
    Animated.sequence([
      Animated.timing(scaleAnim, {
        toValue: 0.85,
        duration: 50,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 1,
        duration: 150,
        useNativeDriver: true,
      }),
    ]).start(() => {
      onPress();
    });
  };
  
  return (
    <TouchableOpacity 
      style={styles.container}
      onPress={handlePress}
      activeOpacity={0.7}
    >
      <Animated.View style={{ transform: [{ scale: scaleAnim }] }}>
        <Bell size={24} color={colors.text} />
        {hasNewMessages && (
          <Animated.View 
            style={[
              styles.badge,
              { transform: [{ scale: pulseAnim }] }
            ]} 
          />
        )}
      </Animated.View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'relative',
    padding: 8,
  },
  badge: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: '#E74C3C',
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
});