import React, {memo, useEffect, useRef} from 'react';
import Animated, {
  withTiming,
  Easing,
  EntryAnimationsValues,
  ExitAnimationsValues,
} from 'react-native-reanimated';
import {Typography, Spinner} from '@components';
import {SPACING} from '@shared/theme';

import {styles} from './styles';

const ANIMATION_DURATION: number = 250;
interface Props {
  text: Nullable<string>;
  showSpinner?: boolean;
}

const customEntering = (value: EntryAnimationsValues) => {
  'worklet';
  const animations = {
    height: withTiming(value.targetHeight, {
      duration: ANIMATION_DURATION,
      easing: Easing.cubic,
    }),
    opacity: withTiming(1, {duration: ANIMATION_DURATION}),
  };
  const initialValues = {
    opacity: 0,
    height: value.targetHeight,
  };
  return {
    initialValues,
    animations,
  };
};

const customExiting = (value: ExitAnimationsValues) => {
  'worklet';
  const animations = {
    height: withTiming(0, {duration: ANIMATION_DURATION, easing: Easing.cubic}),
    opacity: withTiming(0, {duration: ANIMATION_DURATION}),
  };
  const initialValues = {
    height: value.currentHeight,
    opacity: 1,
  };
  return {
    initialValues,
    animations,
  };
};

function AnimatedInfoHeaderComponent({
  text = null,
  showSpinner = false,
}: Props) {
  const lastText = useRef(text || '');

  useEffect(() => {
    if (text) {
      lastText.current = text;
    }
  }, [text]);

  return (
    <Animated.View
      exiting={customExiting}
      entering={customEntering}
      style={styles.container}>
      {showSpinner && <Spinner size={SPACING.x2} />}
      <Typography variant="xs">{text || lastText.current}</Typography>
    </Animated.View>
  );
}

export const AnimatedInfoHeader = memo(AnimatedInfoHeaderComponent);
