import React, {useState} from 'react';
import {ImageStyle, StyleProp, View, ViewStyle} from 'react-native';
import DefaultImage from '@assets/defaultImage.svg';
import {
  CustomImage,
  ImageProps,
} from '@components/Image/components/CustomImage';
import {getTextVariant} from '@components/Image/utils';
import Text from '@components/Text';
import {COLORS} from '@shared/colors';
import {TUserName, getInitialLetters} from '@shared/utils';

import {AvatarBorderVariant, AvatarSize, AvatarSizeType} from './interfaces';
import {styles} from './styles';

export interface AvatarProps extends Omit<ImageProps, 'source' | 'resizeMode'> {
  url?: Nullable<string>;
  name?: TUserName;
  size?: AvatarSize;
  borderVariant?: AvatarBorderVariant;
}

/**
 * @deprecated Use `_HuGo/Avatar` instead
 */
export function Avatar({
  url,
  name,
  style,
  borderVariant = 'none',
  size = 'sm',
  ...props
}: AvatarProps) {
  const [canShowLetters, setCanShowLetters] = useState(false);
  const {nameVariant} = getTextVariant(size);
  const lettersAvatar = getInitialLetters(name);
  const imageSize = AvatarSizeType[size];

  const handleImageError = () => {
    setCanShowLetters(true);
  };

  const propStyles: ImageStyle = {
    width: imageSize,
    height: imageSize,
    borderRadius: imageSize,
    ...(borderVariant !== 'none' ? styles[borderVariant] : {}),
  };

  return url && !canShowLetters ? (
    <CustomImage
      source={{uri: url}}
      style={[propStyles, style]}
      resizeMode="cover"
      onError={handleImageError}
      loaderType="skeleton"
      {...props}
    />
  ) : lettersAvatar.length ? (
    <View
      style={
        [propStyles, styles.lettersContainer, style] as StyleProp<ViewStyle>
      }>
      <Text adjustsFontSizeToFit color={COLORS.WHITE} variant={nameVariant}>
        {lettersAvatar}
      </Text>
    </View>
  ) : (
    <DefaultImage
      width={imageSize}
      height={imageSize}
      style={style as StyleProp<ViewStyle>}
    />
  );
}

export * from './interfaces';
