import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { DIRECTION_TOP, DIRECTION_BOTTOM, scrollToTop, scrollToBottom } from '../../tools/interactivity/scroll';
import Icon from '../icon/Icon';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ButtonPageScroll.scss';

const n = createNamespace('ButtonPageScroll');

const ButtonPageScroll = ({
    direction,
    text,
    hiddenButton,
    hiddenText,
    mobileOnly,
    desktopOnly,
    ...otherProps
}) => {
    const {
        className: extraClass
    } = otherProps;

    const buttonRef = useRef();

    const onClick = () => {
        if (buttonRef.current) {
            buttonRef.current.blur();
        }
        if (direction === DIRECTION_TOP) {
            scrollToTop();
        } else if (direction === DIRECTION_BOTTOM) {
            scrollToBottom();
        }
    };

    const buttonModifiers = [
        !hiddenButton && 'visible',
        mobileOnly && 'mobile-only',
        desktopOnly && 'desktop-only'
    ];

    return (
        <button
            {...n('button', buttonModifiers).withTestId().withClass(extraClass).props}
            type="button"
            onClick={onClick}
            tabIndex="-1"
            ref={buttonRef}
        >
            <span {...n('iconWrapper').props}>
                <Icon
                    {...n('icon').props}
                    type={direction === DIRECTION_BOTTOM ? 'caretDown' : 'caretUp'}
                />
            </span>
            {text && <span {...n('text', hiddenText && 'sr-only').withTestId().props}>{text}</span>}
        </button>
    );
};

ButtonPageScroll.propTypes = {
    text: PropTypes.string,
    direction: PropTypes.oneOf([DIRECTION_TOP, DIRECTION_BOTTOM]),
    hiddenButton: PropTypes.bool,
    hiddenText: PropTypes.bool,
    mobileOnly: PropTypes.bool,
    desktopOnly: PropTypes.bool
};

ButtonPageScroll.defaultProps = {
    text: 'Back to top',
    direction: DIRECTION_TOP,
    hiddenButton: false,
    hiddenText: false,
    mobileOnly: false,
    desktopOnly: false
};

export default ButtonPageScroll;
