import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { TYPE_BUTTON, TYPE_SUBMIT, TYPE_RESET } from '../../constants/buttons';
import './styles/Button.scss';

const n = createNamespace('Button');

const Button = ({
    children,
    type,
    disabled,
    selected,
    active,
    wide,
    onClick,
    size,
    url,
    condensed,
    action,
    buttonType,
    extraClass,
    'data-testid': dataTestId
}) => {
    const modifiers = [type, size, buttonType];
    // if a button is disabled, it won't be set as active
    if (disabled) {
        modifiers.push('disabled');
    } else if (active) {
        modifiers.push('active');
    }
    if (selected) {
        modifiers.push('selected');
    }
    if (condensed) {
        modifiers.push('condensed');
    }
    if (wide) {
        modifiers.push('wide');
    }

    const renderChild = child => (typeof child === 'string' ? <div key={child} {...n('text').withE2EId().props}>{child}</div> : child);

    const onClickHandler = e => {
        if (disabled) { return; }
        if (url) { window.location = url; }
        if (onClick) {
            onClick(e);
        }
    };

    const buttonTestId = dataTestId ? { [createNamespace.TESTID_ATTR]: dataTestId } : n().withTestId('item').withE2EId('item').props;
    const buttonProps = Object.assign(
        n('item', modifiers).withClass(extraClass).props,
        buttonTestId,
        { onClick: onClickHandler }
    );

    return (
        /* eslint-disable react/button-has-type */
        <button {...buttonProps} type={action}>
            {React.Children.map(children, renderChild)}
        </button>
    );
};

export const allowedThemes = ['primary', 'secondary', 'emphasis', 'emphasis-outline', 'emphasisAlt', 'white', 'card'];
export const allowedActions = [TYPE_BUTTON, TYPE_SUBMIT, TYPE_RESET];
export const allowedSizes = ['default', 'small', 'large', 'input'];
export const allowedTypes = ['button', 'link', 'icon'];

Button.propTypes = {
    type: PropTypes.oneOf(allowedThemes),
    disabled: PropTypes.bool,
    selected: PropTypes.bool,
    url: PropTypes.string,
    active: PropTypes.bool,
    wide: PropTypes.bool,
    condensed: PropTypes.bool,
    buttonType: PropTypes.oneOf(allowedTypes),
    action: PropTypes.oneOf(allowedActions),
    onClick: PropTypes.func,
    size: PropTypes.oneOf(allowedSizes),
    extraClass: PropTypes.string,
    'data-testid': PropTypes.string
};

Button.defaultProps = {
    type: 'secondary',
    disabled: false,
    url: undefined,
    selected: false,
    active: false,
    wide: false,
    buttonType: 'button',
    action: TYPE_BUTTON,
    onClick: () => {},
    size: 'default',
    condensed: false,
    extraClass: null,
    'data-testid': ''
};

export default Button;
