import { forwardRef, useState, useCallback, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import classes from './styles.module.scss';
const Headshot = forwardRef((props, ref) => {
  const {
    src,
    alt,
    className,
    ...forwardProps
  } = props;
  const img = useRef();
  const [hasError, setHasError] = useState(false);
  const cbRef = useCallback(node => {
    img.current = node;
    if (!ref) return;
    if (typeof ref === 'function') {
      ref(node);
    } else {
      ref.current = node; // eslint-disable-line
    }
  }, []);
  const setError = useCallback(() => {
    setHasError(true);
  }, []);
  useEffect(() => {
    setHasError(false);
  }, [src]);
  useEffect(() => {
    if (!img.current) return;
    if (!img.current.complete) return;
    setHasError(img.current.naturalWidth === 0);
  });
  if (!src || hasError) return null;
  return <img ref={cbRef} src={src} alt={alt} className={classnames(classes.container, className)} onError={setError} {...forwardProps} />;
});
Headshot.displayName = 'Headshot';
Headshot.defaultProps = {
  src: undefined,
  className: undefined
};
Headshot.propTypes = {
  src: PropTypes.string,
  alt: PropTypes.string.isRequired,
  className: PropTypes.string
};
export default Headshot;