import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import './styles/Alert.scss';
import { createNamespace } from '../../tools/namingTools';
import Icon from '../icon/Icon';

const n = createNamespace('Alert');

export const alertTypes = {
    SUCCESS_ALERT: 'success',
    ERROR_ALERT: 'error'
};

const Alert = ({
    alertMessage,
    type,
    scrollIntoView,
    onClose,
    isGlobal,
    ...otherProps
}) => {
    const [isVisible, setVisible] = useState(true);
    const alertRef = React.createRef();

    // cleanup listeners
    useEffect(() => {
        const handleScrollOnLoad = () => {
            alertRef.current.scrollIntoView({ block: 'start', behavior: 'smooth' });
        };
        if (scrollIntoView) {
            document.addEventListener('DOMContentLoaded', handleScrollOnLoad, false);
        }
        return () => scrollIntoView && document.removeEventListener('DOMContentLoaded', handleScrollOnLoad, false);
    }, [alertRef, scrollIntoView]);

    if (!isVisible) {
        return null;
    }
    const onClick = onClose || (() => setVisible(false));
    return (
        <div ref={alertRef} {...n('alertContainer', [type, isGlobal && 'global']).props} {...otherProps}>
            <div {...n('messageWrapper').props}>
                {alertMessage}
            </div>
            <div {...n('closeIcon').props}>
                <Icon type="close" width="12px" fill="white" onClick={onClick} />
            </div>
        </div>
    );
};

Alert.propTypes = {
    alertMessage: PropTypes.string.isRequired,
    type: PropTypes.string,
    isGlobal: PropTypes.bool,
    scrollIntoView: PropTypes.bool,
    onClose: PropTypes.func
};

Alert.defaultProps = {
    type: null,
    isGlobal: false,
    scrollIntoView: false,
    onClose: null
};

export default Alert;
