import { View, Animated } from 'react-native';
import React from 'react';
import type { StyleProp, ViewStyle, ViewProps } from 'react-native';
import type { ReactElement, ReactNode } from 'react';
import { StyledStatus } from './StyledBadge';

export interface StatusProps extends ViewProps {
  /*
   * The Status Badge's content.
   */
  children: ReactNode;
  /**
   * Whether the Status Badge is visible.
   */
  visible?: boolean;
  /**
   * Visual intent color to apply to Status Badge.
   */
  intent?:
    | 'success'
    | 'warning'
    | 'danger'
    | 'info'
    | 'archived'
    | 'primary'
    | 'neutral';
  /**
   * Additional style.
   */
  style?: StyleProp<ViewStyle>;
  /**
   * Testing id of the component.
   */
  testID?: string;
}

const Status = ({
  children,
  visible = true,
  intent = 'danger',
  style,
  testID,
  ...nativeProps
}: StatusProps): ReactElement => {
  const { current: opacity } = React.useRef<Animated.Value>(
    new Animated.Value(visible ? 1 : 0)
  );
  const isFirstRendering = React.useRef<boolean>(true);

  React.useEffect(() => {
    // Do not run animation on very first rendering
    if (isFirstRendering.current) {
      isFirstRendering.current = false;
      return;
    }

    Animated.timing(opacity, {
      toValue: visible ? 1 : 0,
      duration: 150,
      useNativeDriver: true,
    }).start();
  }, [visible, opacity]);

  return (
    <View {...nativeProps} style={style} testID={testID}>
      {children}
      <StyledStatus
        style={{
          opacity,
          transform: [
            {
              scale: opacity.interpolate({
                inputRange: [0, 1],
                outputRange: [0.5, 1],
              }),
            },
          ],
        }}
        themeIntent={intent}
        testID="status-dot"
      />
    </View>
  );
};

export default Status;
