import React, { useMemo } from 'react';

import { Animated } from 'react-native';
import { StretchyAnimationProps } from '../type';
import { useAnimatedScroll } from '@cleartrip/ct-design-scroll-container';
import { isIOS } from '@cleartrip/ct-design-common-utils';

const StretchyAnimation: React.FC<StretchyAnimationProps> = ({ children, dynamicHeight, iosOnly = true }) => {
  const { scrollY } = useAnimatedScroll() as unknown as { scrollY: Animated.Value };

  const stretchyCarouselStyle = useMemo(() => {
    if (!isIOS() && iosOnly) return undefined;
    return {
      transform: [
        {
          translateY: scrollY.interpolate({
            inputRange: [-dynamicHeight, 0],
            outputRange: [-dynamicHeight / 2, 0],
            extrapolateRight: 'clamp',
          }),
        },
        {
          scale: scrollY.interpolate({
            inputRange: [-dynamicHeight, 0],
            outputRange: [2, 1],
            extrapolateRight: 'clamp',
          }),
        },
      ],
    };
  }, [iosOnly, scrollY, dynamicHeight]);

  if (isIOS() && iosOnly) {
    return <Animated.View style={stretchyCarouselStyle}>{children}</Animated.View>;
  }

  return children;
};

export default StretchyAnimation;
