import { forwardRef, useEffect } from 'react';
import { type ViewProps } from 'react-native';
import Animated, {
  Easing,
  useAnimatedStyle,
  useSharedValue,
  withRepeat,
  withTiming,
} from 'react-native-reanimated';
import { cn } from '@cdx-ui/utils';
import { skeletonVariants } from './styles';

export interface SkeletonProps extends ViewProps {
  className?: string;
  /** Pulse animation duration in milliseconds. @default 1000 */
  duration?: number;
}

export const Skeleton = forwardRef<Animated.View, SkeletonProps>(
  ({ className, style, duration = 1000, ...props }, ref) => {
    const opacity = useSharedValue(1);

    useEffect(() => {
      opacity.set(
        withRepeat(withTiming(0.35, { duration, easing: Easing.inOut(Easing.ease) }), -1, true),
      );
    }, [duration, opacity]);

    const animatedStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));

    return (
      <Animated.View
        ref={ref}
        className={cn(skeletonVariants(), className)}
        style={[animatedStyle, style]}
        {...props}
      />
    );
  },
);

Skeleton.displayName = 'Skeleton';
