import React, { useRef, useEffect } from 'react';
import { Animated } from 'react-native';

/**
 * Wrap any component to give it a subtle fade+slide entrance.
 *
 * Props:
 *   delay    - ms delay before animation starts (default 0)
 *   duration - ms animation duration (default 350)
 *   slide    - px to slide up from (default 10)
 *   trigger  - change this value to replay the animation (e.g. a counter)
 *   style    - additional style
 */
export default function FadeIn({ children, delay = 0, duration = 350, slide = 10, trigger, style }) {
  const fade = useRef(new Animated.Value(0)).current;
  const translateY = useRef(new Animated.Value(slide)).current;

  useEffect(() => {
    // Reset and replay
    fade.setValue(0);
    translateY.setValue(slide);
    Animated.parallel([
      Animated.timing(fade, { toValue: 1, duration, delay, useNativeDriver: true }),
      Animated.timing(translateY, { toValue: 0, duration, delay, useNativeDriver: true }),
    ]).start();
  }, [trigger]);

  return (
    <Animated.View style={[{ opacity: fade, transform: [{ translateY }] }, style]}>
      {children}
    </Animated.View>
  );
}
