import React from 'react';
import type { StyleProp, ViewStyle } from 'react-native';
import { Animated } from 'react-native';

import { useTheme } from '../../theme';
import {
  StyledPageControl,
  StyledPageControlAnimatedView,
} from './StyledPageControl';

export interface PageControlProps {
  /**
   * The number of pages to display
   */
  numberOfPages: number;
  /**
   * The current page to display
   */
  currentPage: number;
  /**
   * Additional styles
   */
  style?: StyleProp<ViewStyle>;
  /**
   * Testing id of the component.
   */
  testID?: string;
}
const PageControl = ({
  numberOfPages,
  currentPage = 0,
  testID,
  style,
}: PageControlProps) => {
  const theme = useTheme();
  const animatedValue = React.useRef(new Animated.Value(currentPage)).current;

  React.useEffect(() => {
    Animated.spring(animatedValue, {
      toValue: currentPage,
      useNativeDriver: false, // Native driver does not support animating width, it will cause the app to crash if set to true
    }).start();
  }, [currentPage]);

  return (
    <StyledPageControl testID={testID} style={style}>
      {new Array(numberOfPages).fill('').map((_, index) => {
        const inputRange = [index - 1, index, index + 1];

        const indicatorWidth = animatedValue.interpolate({
          inputRange,
          outputRange: [
            theme.space.small,
            theme.space.large,
            theme.space.small,
          ],
          extrapolate: 'clamp',
        });

        const opacity = animatedValue.interpolate({
          inputRange,
          outputRange: [0.5, 1, 0.5],
          extrapolate: 'clamp',
        });

        return (
          <StyledPageControlAnimatedView
            accessibilityState={{ selected: index === currentPage }}
            style={[{ width: indicatorWidth, opacity }]}
            key={index.toString()}
            testID={`page-control-indicator${index}`}
          />
        );
      })}
    </StyledPageControl>
  );
};

export default PageControl;
