import React, { useState } from 'react';
import { AvatarWrap } from './AvatarWrap';
import redError from '@/assets/icon/redError.svg';

export interface AvatarProps {
  imgSrc: string;
  onClick?: () => void;
  fallback?: string;
  size?: 'large' | 'default' | 'small' | number;
  borderless?: boolean;
}

const Avatar: React.FC<AvatarProps> = ({
  imgSrc,
  onClick,
  fallback = redError,
  size = 'default',
  borderless = false,
}) => {
  const [imageLoadedError, setImageLoadedError] = useState(false);
  let sizeNumber = 40;
  if (typeof size === 'string') {
    if (parseInt(size, 10).toString() === size) {
      sizeNumber = parseInt(size, 10);
    } else {
      switch (size) {
        case 'default':
          sizeNumber = 40;
          break;
        case 'large':
          sizeNumber = 64;
          break;
        case 'small':
          sizeNumber = 32;
          break;
        default:
          sizeNumber = 40;
          break;
      }
    }
  } else {
    sizeNumber = size;
  }

  return (
    <AvatarWrap size={sizeNumber} borderless={borderless}>
      <div
        className="avatarContainer"
        onClick={e => {
          e.stopPropagation();
          onClick?.();
        }}
      >
        <img
          className="avatar"
          src={imageLoadedError ? fallback : imgSrc}
          onError={() => {
            setImageLoadedError(true);
          }}
        />
      </div>
    </AvatarWrap>
  );
};

export default Avatar;
