import { forwardRef } from 'react';
import { Image, View } from 'react-native';
import type { ImageSourcePropType } from 'react-native';
import type { RsSkinlessImageProps } from '../../types/props';

type ViewRef = View;

function normalizeSource(
  source: ImageSourcePropType | { uri: string }
): ImageSourcePropType {
  if (typeof source === 'string') {
    return { uri: source };
  }
  return source as ImageSourcePropType;
}

const RsImage = forwardRef<ViewRef, RsSkinlessImageProps>(
  ({ source, resizeMode, style, alt, onLoad, onError }, ref) => {
    return (
      <View ref={ref} style={style}>
        <Image
          source={normalizeSource(source)}
          resizeMode={resizeMode}
          accessibilityLabel={alt}
          onLoad={onLoad}
          onError={onError ? () => onError() : undefined}
          style={{ width: '100%', height: '100%' }}
        />
      </View>
    );
  }
);

RsImage.displayName = 'RsImage';

export default RsImage;
