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'
};
export const alertTypesEnum = Object.values(alertTypes);

const Alert = ({
    alertMessage,
    type,
    scrollIntoView,
    onClose,
    isGlobal,
    closeAlert,
    ...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>
            <button {...n('closeButton').props} type="button" onClick={onClick}>
                <Icon type="close" width="12px" fill="white" />
                <span {...n('closeButtonText').props}>{closeAlert}</span>
            </button>
        </div>
    );
};

Alert.propTypes = {
    alertMessage: PropTypes.string.isRequired,
    type: PropTypes.oneOf(alertTypesEnum),
    isGlobal: PropTypes.bool,
    scrollIntoView: PropTypes.bool,
    onClose: PropTypes.func,
    closeAlert: PropTypes.string
};

Alert.defaultProps = {
    type: null,
    isGlobal: false,
    scrollIntoView: false,
    onClose: null,
    closeAlert: 'Close alert'
};

export default Alert;
