import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";

import Box from "../Box";

import { IntialsBox, Img, UppercaseText } from "./styledComponents";

const Avatar = ({ url, initials, size, ...styleProps }) => {
  const [isValidUrl, setIsValidUrl] = useState(false);

  useEffect(() => {
    if (!url) return;
    const s = document.createElement("IMG");
    s.src = url;
    s.onload = () => {
      setIsValidUrl(true);
    };
  }, [url]);

  return (
    <Box
      data-testid="avatar-wrapper"
      padding="zero"
      height={size}
      alignItems="center"
      {...styleProps}
    >
      {isValidUrl ? (
        <Img src={url} data-testid="icon" size={size} />
      ) : (
        <IntialsBox data-testid="avatar-box" size={size}>
          <UppercaseText
            variant="h3.semi-bold"
            color="grey.deep"
            data-testid="avatar-text"
          >
            {initials}
          </UppercaseText>
        </IntialsBox>
      )}
    </Box>
  );
};

Avatar.propTypes = {
  /** URL to fetch Avatar/Profile image */
  url: PropTypes.string,
  /** Initials text is used to show in the absense of URL or during loading */
  initials: PropTypes.string.isRequired,
  /** Size of the Avatar */
  size: PropTypes.string,
};

Avatar.defaultProps = {
  url: "",
  size: "40px",
};

export default React.memo(Avatar);
