import React, { useEffect, useRef } from 'react';
import type { ResponsiveValue } from '@shopify/restyle';
import { Animated, Easing } from 'react-native';
import type { Theme } from '../../theme/theme';
import { Box } from '../Box';
import { LoadingDot } from './LoadingDot';

export interface ILoadingContainer {
  show?: boolean;
  full?: boolean;
  count?: number;
  colorDot?: ResponsiveValue<keyof Theme['colors'], Theme>;
  pt?: ResponsiveValue<keyof Theme['spacing'], Theme>;
  pb?: ResponsiveValue<keyof Theme['spacing'], Theme>;
  size?: 'normal' | 'small';
}

export const LoadingContainer = ({
  colorDot,
  show = true,
  count = 3,
  pt = 'spacing-l',
  pb = 'spacing-l',
  size,
}: ILoadingContainer) => {
  const progress = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (show) {
      const animation = Animated.timing(progress, {
        duration: 1200,
        easing: Easing.out(Easing.ease),
        toValue: 1,
        isInteraction: true,
        useNativeDriver: true,
      });

      Animated.loop(animation).start();
    }
  }, [progress, show]);

  if (!show) return null;

  return (
    <Box
      zIndex={1}
      justifyContent="center"
      alignItems="flex-start"
      flexDirection="row"
      paddingTop={pt}
      paddingBottom={pb}
    >
      {new Array(count).fill(0).map((_, index) => {
        return (
          <LoadingDot
            key={index}
            count={count}
            progress={progress}
            index={index}
            colorDot={colorDot}
            size={size}
          />
        );
      })}
    </Box>
  );
};
