import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Icon from '../icon/Icon';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/StatusMessage.scss';

const n = createNamespace('StatusMessage');

const StatusMessage = ({
    title,
    details,
    icon,
    scrollIntoView
}) => {
    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]);

    return (
        <section ref={alertRef} {...n('container').props}>
            <Icon {...n('icon').props} type={icon} />
            <div {...n('messageWrapper').props}>
                <span {...n('title').withTestId().props}>{title}</span>
                <span {...n('details').withTestId().props}>{details}</span>
            </div>
        </section>
    );
};

StatusMessage.propTypes = {
    title: PropTypes.string.isRequired,
    details: PropTypes.string,
    icon: PropTypes.string,
    scrollIntoView: PropTypes.bool
};

StatusMessage.defaultProps = {
    details: null,
    scrollIntoView: false,
    icon: 'frown'
};

export default StatusMessage;
