import React, {useEffect} from 'react';
import {StyleSheet} from 'react-native';
import {useTranslation} from 'react-i18next';
import Animated, {
  Easing,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import Text from '@components/Text';
import ActivityIndicator from '@components/ActivityIndicator';
import {useAppSelector} from '@redux/utils';
import {BORDER_RADIUS, SPACING} from '@shared/theme';
import {COLORS} from '@shared/colors';

const HIDDEN_TOP = -64;

export function SyncLoader() {
  const {t} = useTranslation();
  const isSyncRunning = useAppSelector(({chats}) => chats.events.isSyncRunning);
  const sharedValue = useSharedValue(HIDDEN_TOP);

  useEffect(() => {
    sharedValue.value = withTiming(isSyncRunning ? SPACING.x2 : HIDDEN_TOP, {
      duration: 250,
      easing: Easing.exp,
    });
  }, [isSyncRunning, sharedValue]);

  const animatedStyles = useAnimatedStyle(() => ({
    top: sharedValue.value,
  }));

  return (
    <Animated.View style={[styles.container, animatedStyles]}>
      <ActivityIndicator size="small" />
      <Text>{t('general.updating')}</Text>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    alignSelf: 'center',
    zIndex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.WHITE,
    borderRadius: BORDER_RADIUS.m,
    paddingHorizontal: SPACING.x1,
    paddingVertical: SPACING['x0.5'],
    marginVertical: SPACING.x1,
    flexDirection: 'row',
    gap: SPACING.x1,
  },
});
