import React, {memo, useCallback} from 'react';
import {StyleProp, View, ViewStyle} from 'react-native';
import {useTranslation} from 'react-i18next';
import * as Haptics from 'expo-haptics';
import {IconPlus} from '@tabler/icons-react-native';
import {EaseView, SpringTransition} from 'react-native-ease';
import {Pressable, Typography} from '@components';
import {SpringTransitionBouncyConfig} from '@modules/chats/constants';
import {ICON_SIZES, useTheme} from '@shared/theme';
import {commonStyles} from '@shared/styles';
import {isIos} from '@shared/utils';

import {styles} from './styles';

export interface ContextReactionsOption {
  name: string;
  emoji: string;
  isReacted?: boolean;
  onPress: () => void;
}
interface Props {
  reactions: ContextReactionsOption[];
  style?: StyleProp<ViewStyle>;
}

function getAnimationConfig(index: number): SpringTransition {
  return {
    ...SpringTransitionBouncyConfig,
    delay: (index + 1) * 50,
  };
}

const ContextReactionsComponent = ({reactions, style}: Props) => {
  const {theme} = useTheme();
  const {t} = useTranslation();

  const handlePress = useCallback(
    (onPress: () => void) => () => {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
      onPress();
    },
    [],
  );

  return (
    <View
      accessible={false}
      accessibilityRole="menu"
      accessibilityLabel={t('chat.reactions')}
      style={[
        styles.menu,
        isIos
          ? commonStyles.shadow
          : {...styles.menuBorder, borderColor: theme.border.neutral.default},
        style,
      ]}>
      {reactions.map(({name, emoji, onPress, isReacted}, index) =>
        name === 'more' ? (
          <Pressable
            key={name}
            accessibilityLabel={t('chat.open_reaction_picker')}
            onPress={onPress}
            style={styles.more}>
            <EaseView
              initialAnimate={{scale: 0.3, opacity: 0}}
              animate={{scale: 1, opacity: 1}}
              transition={getAnimationConfig(index)}>
              <IconPlus
                size={ICON_SIZES.x4}
                color={theme.text.neutral.default}
              />
            </EaseView>
          </Pressable>
        ) : (
          <Pressable
            key={name}
            accessibilityLabel={t('chat.react_with', {reaction: name})}
            style={[
              styles.menuItem,
              isReacted && {
                backgroundColor: theme.background.elements.grey,
              },
            ]}
            onPress={handlePress(onPress)}>
            <EaseView
              initialAnimate={{scale: 0.1, opacity: 0}}
              animate={{scale: 1, opacity: 1}}
              transition={getAnimationConfig(index)}>
              <Typography style={styles.emoji}>{emoji}</Typography>
            </EaseView>
          </Pressable>
        ),
      )}
    </View>
  );
};

export const ContextReactions = memo(ContextReactionsComponent);
