import React, {useMemo} from 'react';
import {StyleProp, StyleSheet, View, ViewStyle} from 'react-native';
import {IconChevronDown} from '@tabler/icons-react-native';
import Animated, {
  runOnJS,
  useAnimatedStyle,
  SharedValue,
  useSharedValue,
  withTiming,
  useAnimatedReaction,
} from 'react-native-reanimated';
import {Gesture, GestureDetector} from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
import {BORDER_RADIUS, SPACING, useTheme} from '@shared/theme';

type Props = {
  isVisible: SharedValue<boolean>;
  onPress: () => void;
  style: StyleProp<ViewStyle>;
};

export default function ScrollToBottomButton({
  style,
  isVisible,
  onPress,
}: Props) {
  const {theme} = useTheme();
  const fadeAnim = useSharedValue(0);

  useAnimatedReaction(
    () => isVisible.get(),
    visible => {
      fadeAnim.value = withTiming(visible ? 1 : 0, {duration: 300});
    },
  );

  const singleTap = useMemo(
    () =>
      Gesture.Tap()
        .onStart(() => {
          runOnJS(onPress)();
        })
        .onBegin(() => {
          runOnJS(Haptics.selectionAsync)();
        })
        .onEnd(() => {
          runOnJS(Haptics.impactAsync)(Haptics.ImpactFeedbackStyle.Rigid);
        }),
    [onPress],
  );

  const animatedStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {
        opacity: 0,
      };
    }
    return {
      opacity: fadeAnim.value,
    };
  });

  return (
    <Animated.View
      style={[style, animatedStyle]}
      pointerEvents={isVisible ? 'auto' : 'none'}>
      <GestureDetector gesture={singleTap}>
        <View
          // TODO(product): Define accessibilityLabel (e.g. translation key) for this button
          testID="scroll-to-bottom-button"
          style={[
            styles.container,
            {
              backgroundColor: theme.button.background.secondary.default,
              borderColor: theme.border.neutral.brand,
            },
          ]}>
          <IconChevronDown color={theme.text.neutral.brand} />
        </View>
      </GestureDetector>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderWidth: 1,
    borderRadius: BORDER_RADIUS.xl,
    padding: SPACING.x1,
  },
});
