import React, { useState } from 'react';
import type {
  ImageSourcePropType,
  StyleProp,
  ViewProps,
  ViewStyle,
} from 'react-native';
import {
  StyledImage,
  StyledWrapper,
  StyledText,
  StyledTextWrapper,
} from './StyledAvatar';

export interface AvatarProps extends ViewProps {
  /**
   * Callback function when pressing component.
   */
  onPress?: () => void;
  /**
   * Image source to be displayed on avatar.
   */
  source?: ImageSourcePropType;
  /**
   * Renders title in the placeholder.
   */
  title?: string;
  /**
   * Visual intent of the Avatar. Defaults to `'neutral'`.
   */
  intent?: 'neutral' | 'primary' | 'info' | 'danger' | 'success' | 'warning';
  /**
   * Size of the avatar.
   */
  size?:
    | 'small'
    | 'medium'
    | 'large'
    | 'xlarge'
    | 'xxlarge'
    | 'xxxlarge'
    | 'xxxxlarge'
    | 'xxxxxlarge';
  /**
   * Additional style.
   */
  style?: StyleProp<ViewStyle>;
  /**
   * Testing id of the component.
   */
  testID?: string;
}

const Avatar = ({
  onPress,
  source,
  testID,
  style,
  title,
  size = 'small',
  intent = 'neutral',
}: AvatarProps) => {
  const [hasImageError, setHasImageError] = useState(false);

  if (title === undefined && source === undefined) return null;
  return (
    <StyledWrapper
      testID={testID}
      onPress={onPress}
      disabled={onPress === undefined}
      themeIntent={intent}
      themeSize={size}
      style={style}
    >
      {(source === undefined || hasImageError) && (
        <StyledTextWrapper>
          <StyledText themeSize={size}>{title}</StyledText>
        </StyledTextWrapper>
      )}
      {source !== undefined && (
        <StyledImage
          resizeMode="cover"
          source={source}
          themeSize={size}
          onLoad={() => setHasImageError(false)}
          onError={() => setHasImageError(true)}
          testID="avatar-image"
        />
      )}
    </StyledWrapper>
  );
};

export default Avatar;
