import {useFocusEffect} from '@react-navigation/native';
import {animated, useSpring} from '@react-spring/native';
import {useEffect} from 'react';
import {Dimensions, View} from 'react-native';

const AnimationView = animated(View);

export const FadeInView = (props: any) => {
  const [motionProps, api] = useSpring(
    () => ({
      from: {
        opacity: 0,
      },
    }),
    [],
  );

  useFocusEffect(() => {
    api.start({
      to: [
        {
          opacity: 1,
        },
      ],
    });
    return () => {
      api.start({
        to: [
          {
            opacity: 0,
          },
        ],
      });
    };
  });

  return (
    <AnimationView // Special animatable View
      style={{
        flex: 1,
        opacity: motionProps.opacity, // Bind opacity to animated value
      }}>
      {props.children}
    </AnimationView>
  );
};

export const SlideFromLeftView = (props: any) => {
  let SCREEN_WIDTH = Dimensions.get('window').width;

  const [motionProps, api] = useSpring(
    () => ({
      from: {
        translateX: -SCREEN_WIDTH,
      },
    }),
    [],
  );

  useFocusEffect(() => {
    api.start({
      to: [
        {
          translateX: 0,
        },
      ],
    });
    return () => {
      SCREEN_WIDTH = Dimensions.get('window').width;
      api.start({
        to: [
          {
            translateX: -SCREEN_WIDTH,
          },
        ],
      });
    };
  });

  return (
    <AnimationView // Special animatable View
      style={{
        flex: 1,
        transform: [{translateX: motionProps.translateX}],
      }}>
      {props.children}
    </AnimationView>
  );
};

export const SlideFromRightView = (props: any) => {
  let SCREEN_WIDTH = Dimensions.get('window').width;

  const [motionProps, api] = useSpring(
    () => ({
      from: {
        translateX: SCREEN_WIDTH,
      },
    }),
    [],
  );

  useFocusEffect(() => {
    api.start({
      to: [
        {
          translateX: 0,
        },
      ],
    });
    return () => {
      SCREEN_WIDTH = Dimensions.get('window').width;
      api.start({
        to: [
          {
            translateX: SCREEN_WIDTH,
          },
        ],
      });
    };
  });

  return (
    <AnimationView // Special animatable View
      style={{
        flex: 1,
        transform: [{translateX: motionProps.translateX}],
      }}>
      {props.children}
    </AnimationView>
  );
};
