import { forwardRef, memo } from 'react';
import type { FC } from 'react';
import clsx from 'clsx';

import MuiAvatar from '@mui/material/Avatar';
import { styled } from '@mui/material/styles';

import { ASSETS_URL } from '../../consts/common';
import { CustomIcon } from '../custom-icon';
import type { Theme } from '../@styles/theme-provider';

import type { AvatarProps } from './types';

interface StyledAvatarProps {
  backgroundColor?: AvatarProps['backgroundColor'];
  color?: AvatarProps['color'];
  customSize?: AvatarProps['customSize'];
}

const StyledAvatar = styled(MuiAvatar, {
  shouldForwardProp: prop => prop !== 'backgroundColor' && prop !== 'color' && prop !== 'customSize'
})<StyledAvatarProps>(
  ({ backgroundColor, color, customSize, theme }: StyledAvatarProps & { theme: Theme }) => ({
    ...theme.typography.caption2,
    backgroundColor,
    color,
    ...(customSize && {
      fontSize: Math.max(8, customSize * (3 / 8)),
      width: customSize,
      height: customSize
    }),
    '&.small': {
      fontSize: theme.spacing(12 / 8),
      width: theme.spacing(3),
      height: theme.spacing(3)
    },
    '&.medium': {
      fontSize: theme.spacing(14 / 8),
      width: theme.spacing(4),
      height: theme.spacing(4)
    },
    '&.large': {
      fontSize: theme.spacing(16 / 8),
      width: theme.spacing(5),
      height: theme.spacing(5)
    },
    '&.xlarge': {
      fontSize: theme.spacing(36 / 8),
      width: theme.spacing(13),
      height: theme.spacing(13)
    },
    '& .avatarIcon': {
      color: 'inherit',
      width: '50%',
      height: '50%',
      '& > div': {
        width: '100%',
        height: '100%'
      }
    }
  })
);

const Avatar: FC<AvatarProps> = forwardRef((props: AvatarProps, ref) => {
  const {
    size,
    customSize,
    initials,
    backgroundColor,
    color,
    src,
    emailVerified,
    icon,
    className,
    ...others
  } = props;

  return (
    <StyledAvatar
      ref={ref}
      src={emailVerified ? src : undefined}
      className={clsx(!customSize && size, className)}
      {...others}
      backgroundColor={backgroundColor}
      color={color}
      customSize={customSize}
    >
      {emailVerified && initials && !src
        ? initials
        : !emailVerified && (
            <CustomIcon
              color={color}
              className="avatarIcon"
              src={`${ASSETS_URL}/icons/icon_member_pending.svg`}
            />
          )}
      {icon?.src && (
        <CustomIcon color={color} {...icon} className={clsx('avatarIcon', icon.className)} />
      )}
    </StyledAvatar>
  );
});

Avatar.defaultProps = {
  size: 'medium',
  emailVerified: true
};

const m = memo(Avatar);
export { m as Avatar };
