import React, { useState, useCallback, useEffect } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { useContainerWidth } from '../../tools/widths/useContainerWidth';
import { bSmall, bMedium } from '../../constants/breakpoints';
import './styles/StickyBannerContainer.scss';

const n = createNamespace('StickyBannerContainer');
const StickyBannerContainer = ({ content, stickyBannerContent }) => {
    const [containerRef, containerWidth] = useContainerWidth();
    const isMobile = Boolean(containerWidth && containerWidth < bSmall);
    const isMobileXL = Boolean(containerWidth && containerWidth < bMedium);
    const modifiers = [isMobileXL ? 'sticky-bottom' : 'sticky-top'];
    const [isShadowVisible, setShadowVisible] = useState(false);
    const containerModifiers = [isMobileXL && 'with-preview-sticky-bottom'];

    const shouldDisplayShadow = useCallback(() => () => {
        if (isMobile) {
            return true;
        }
        return !isMobileXL ? window.scrollY > 0 : false;
    }, [isMobileXL, isMobile]);

    const onScroll = useCallback(() => {
        setShadowVisible(shouldDisplayShadow());
    }, [shouldDisplayShadow]);

    useEffect(() => {
        onScroll();
        window.addEventListener('scroll', onScroll);

        return () => {
            window.removeEventListener('scroll', onScroll);
        };
    }, [onScroll]);

    if (isShadowVisible) {
        modifiers.push('with-boxshadow');
    }

    const renderStickyBanner = () => (
        <div {...n('banner', modifiers).withTestId().props}>
            <div {...n('banner-shadow', modifiers).withTestId().props}>
                <div {...n('banner-content').withTestId().props}>
                    {stickyBannerContent}
                </div>
            </div>
        </div>
    );

    return (
        <div {...n('container', containerModifiers).withTestId().props} ref={containerRef}>
            {!isMobileXL && renderStickyBanner()}
            <div {...n('content').withTestId().props}>
                {content}
            </div>
            {isMobileXL && renderStickyBanner()}
        </div>

    );
};

StickyBannerContainer.propTypes = {
    content: PropTypes.node,
    stickyBannerContent: PropTypes.node
};

StickyBannerContainer.defaultProps = {
    content: null,
    stickyBannerContent: null
};
export default StickyBannerContainer;
