import React from 'react';
import { TouchableOpacity, Text, StyleSheet, Dimensions } from 'react-native';
import Animated, { FadeIn, FadeOut } from 'react-native-reanimated';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { Colors } from 'src/theme';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

interface MessagePosition {
  x: number;
  y: number;
  isMine: boolean;
  width: number;
  height: number;
}

interface ReactionBarProps {
  messagePosition: MessagePosition | null;
  selectedMessage: any;
  reactionEmojis: string[];
  handleReactionPress: (emoji: string, messageId: number) => void;
  openEmojiSelector: () => void;
}

const ReactionBar: React.FC<ReactionBarProps> = ({
  messagePosition,
  selectedMessage,
  reactionEmojis,
  handleReactionPress,
  openEmojiSelector
}) => {
  const insets = useSafeAreaInsets();

  const getPosition = () => {
    if (!messagePosition) return {};

    const spaceAbove = messagePosition.y - insets.top;
    const shouldFix = spaceAbove < 60;

    return shouldFix ? { top: insets.top + 8 } : { top: messagePosition.y - 60 + 8 };
  };

  if (!selectedMessage || !messagePosition) return null;
  return (
    <Animated.View
      entering={FadeIn}
      exiting={FadeOut}
      style={[
        styles.reactionBar,
        getPosition(),
        {
          left: messagePosition?.isMine
            ? Dimensions.get('window').width * 0.25 - 8
            : messagePosition?.x,
          alignSelf: messagePosition.isMine ? 'flex-end' : 'flex-start'
        }
      ]}
    >
      {reactionEmojis.map((emoji) => (
        <TouchableOpacity
          key={emoji}
          onPress={() => handleReactionPress(emoji, selectedMessage?.currentMessage?._id)}
        >
          <Text style={styles.reactionEmoji}>{emoji}</Text>
        </TouchableOpacity>
      ))}
      <TouchableOpacity onPress={() => openEmojiSelector()} style={styles.addReactionButton}>
        <MaterialCommunityIcons name="plus" size={28} color={Colors.LIGHT_GRAY} />
      </TouchableOpacity>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  reactionBar: {
    position: 'absolute',
    width: Dimensions.get('window').width * 0.75,
    flexDirection: 'row',
    backgroundColor: 'rgba(255, 255, 255, 1)',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderRadius: 20,
    padding: 5,
    paddingHorizontal: 12,
    zIndex: 1000,
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 5,
    elevation: 5
  },
  reactionEmoji: {
    fontSize: 28
  },
  addReactionButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: Colors.FILL_LIGHT,
    borderRadius: 15,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY,
    width: 30,
    height: 30
  }
});

export default ReactionBar;
