import React, {ReactNode} from 'react';
import {StyleProp, ViewStyle} from 'react-native';
import Animated, {
  Extrapolation,
  interpolate,
  useAnimatedStyle,
} from 'react-native-reanimated';
import {SPACING} from '@shared/theme';

import {useAnimatedValue} from '../../hooks/useAnimatedValueContext';
import {TABS_HEADER_HEIGHT} from '../../constants';

const TAB_MAX_HEIGHT = TABS_HEADER_HEIGHT + SPACING.x2;

interface Props {
  children: ReactNode;
  style?: StyleProp<ViewStyle>;
}

export function AnimatedTabsHeader({children, style}: Props) {
  const animatedValue = useAnimatedValue();
  const headerTranslateY = animatedValue?.headerTranslateY;
  const headerAnimatedStyle = useAnimatedStyle(() => {
    if (!animatedValue?.tabAnimatedValue) {
      return {};
    }

    const height = interpolate(
      animatedValue.tabAnimatedValue.value,
      [0, 100],
      [TAB_MAX_HEIGHT, 0],
      Extrapolation.CLAMP,
    );

    const translateY = interpolate(
      animatedValue.tabAnimatedValue.value,
      [0, 100],
      [0, -TAB_MAX_HEIGHT],
      Extrapolation.CLAMP,
    );

    return {
      overflow: 'hidden',
      height,
      transform: [{translateY}],
    };
  });

  return (
    <Animated.View
      style={[
        headerAnimatedStyle,
        style,
        {transform: [{translateY: headerTranslateY?.value || 0}]},
      ]}>
      {children}
    </Animated.View>
  );
}
