import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import ReactComponent from 'Shared/PropTypes/ReactComponent';

const states = {
    Loading: 'loading',
    Loaded: 'loaded',
    Error: 'error',
};
const isLoading = state => state === states.Loading;
const isError = state => state === states.Error;

const initialState = states.Loading;

export const ImageLoader = ({ src, fallbackElement, ProgressComponent, imgProps }) => {
    const [loadState, setLoadState] = useState(initialState);
    useEffect(() => {
        setLoadState(initialState);
    }, [src]);
    if (isError(loadState) && fallbackElement) {
        return fallbackElement;
    }
    return (
        <React.Fragment>
            <img
                src={src}
                onError={() => setLoadState(states.Error)}
                onLoad={() => setLoadState(states.Loaded)}
                alt={src}
                {...imgProps}
            />
            {ProgressComponent && <ProgressComponent loading={isLoading(loadState)} />}
        </React.Fragment>
    );
};

ImageLoader.defaultProps = {
    fallbackElement: null,
    ProgressComponent: null,
    imgProps: null,
};

ImageLoader.propTypes = {
    src: PropTypes.string.isRequired,
    ProgressComponent: ReactComponent,
    fallbackElement: PropTypes.element,
    imgProps: PropTypes.object,
};
