import { useEffect, type ReactNode } from 'react';
import type { LayoutChangeEvent } from 'react-native';
import Animated, { Easing, useAnimatedStyle, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated';

import { makeStyles } from '@cleartrip/ct-design-style-manager';

const styledClass = makeStyles(() => ({
  root: {
    position: 'absolute',
    top: -14,
    left: 0,
    overflow: 'hidden',
    flexDirection: 'row',
    alignItems: 'center',
  },
}));

const DURATION_MS = 5000;
const REPEAT_COUNT = 2;

export const AnimatedContainer = ({ children }: { children: ReactNode }) => {
  const progress = useSharedValue(0);
  const measuredWidth = useSharedValue(0);

  useEffect(() => {
    progress.value = withRepeat(withTiming(1, { duration: DURATION_MS, easing: Easing.linear }), REPEAT_COUNT, false);
  }, [progress]);

  const animatedStyle = useAnimatedStyle(() => {
    const w = Math.max(measuredWidth.value, 1);
    const p = progress.value;
    const translateX = -0.5 * w + p * 4.5 * w;
    const opacity = p <= 0.8 ? 1 + ((0.3 - 1) * p) / 0.8 : 0.3 + ((0 - 0.3) * (p - 0.8)) / 0.2;

    return {
      transform: [{ translateX }],
      opacity,
    };
  });

  return (
    <Animated.View
      onLayout={(e: LayoutChangeEvent) => {
        measuredWidth.value = e.nativeEvent.layout.width;
      }}
      style={[styledClass.root, animatedStyle]}
    >
      {children}
    </Animated.View>
  );
};

export default AnimatedContainer;
