import React, {useEffect} from 'react';
import {useTranslation} from 'react-i18next';
import Animated, {
  Easing,
  useAnimatedStyle,
  useSharedValue,
  withRepeat,
  withTiming,
} from 'react-native-reanimated';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import Pill from '@components/Pill';
import {SPACING} from '@shared/theme';

import {styles} from './styles';

const ANIMATION_DURATION = 1000;

interface Props {
  isLive: boolean;
}

function LiveIndicator({isLive}: Props) {
  const {t} = useTranslation();
  const liveAnimation = useSharedValue(1);
  const {top} = useSafeAreaInsets();
  const maxTop = Math.max(top, SPACING.x2);

  useEffect(() => {
    if (isLive) {
      liveAnimation.value = withRepeat(
        withTiming(0, {duration: ANIMATION_DURATION, easing: Easing.linear}),
        -1,
        true,
      );
    } else {
      liveAnimation.value = withTiming(1, {duration: ANIMATION_DURATION});
    }
  }, [isLive, liveAnimation]);

  const liveAnimationStyle = useAnimatedStyle(() => ({
    opacity: liveAnimation.value,
  }));

  return isLive ? (
    <Animated.View
      style={[styles.container, {top: maxTop}, liveAnimationStyle]}>
      <Pill variant="error" label={t('livestream.live')} />
    </Animated.View>
  ) : null;
}

export default LiveIndicator;
