import React, {useEffect, useRef} from 'react';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import {Typography} from '@components/_core/Typography';
import {useTheme} from '@shared/theme';
import {secondsToString} from '@shared/utils';

import {styles} from './styles';

interface Props {
  duration: number;
  show: boolean;
}

export function DurationLabel({duration, show}: Props) {
  const intervalRef = useRef<NodeJS.Timeout>(undefined);
  const {theme} = useTheme();
  const sharedValue = useSharedValue(0);
  const containerStyle = useAnimatedStyle(() => ({opacity: sharedValue.value}));

  useEffect(() => {
    if (show) {
      sharedValue.value = withTiming(1);
      intervalRef.current = setTimeout(() => {
        sharedValue.value = withTiming(0, {duration: 500});
      }, 5000);
    }

    return () => {
      clearTimeout(intervalRef.current);
    };
  }, [sharedValue, show]);

  return show ? (
    <Animated.View style={[styles.container, containerStyle]}>
      <Typography color={theme.text.neutral.inverted} variant="xxxs">
        {secondsToString(duration)}
      </Typography>
    </Animated.View>
  ) : null;
}
