import { noImg } from './no-image';

export interface ImageProps {
    defaultSrc?: string;
}

const Image: React.FC<
    ImageProps & React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>
> = (props) => {
    const { defaultSrc } = props;

    const elementProps = Object.assign({}, props);
    delete elementProps.defaultSrc;

    const handleImgErrorEvent = (e: React.SyntheticEvent<HTMLImageElement>) => {
        const target = e.target as HTMLImageElement;
        target.onerror = null;
        target.src = defaultSrc ? defaultSrc : noImg;
    };

    return <img {...elementProps} onError={(e) => handleImgErrorEvent(e)} />;
};

Image.displayName = 'Image';

export default Image;
