import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import {Button} from '../../Button';
import {Icon} from '../../Icon';
import {Block} from '../../Block';
import {KeyNames} from '../../../../utils/constants';

export class TimeNumberEditor extends React.PureComponent {
    static propTypes = {
        increaseButtonLabel: PropTypes.string.isRequired,
        decreaseButtonLabel: PropTypes.string.isRequired,
        value: PropTypes.number,
        onChange: PropTypes.func.isRequired,
        onShiftTabAwait: PropTypes.func,
        testAutomationId: PropTypes.string.isRequired,
        valueDisplayFormat: PropTypes.func
    };

    static defaultProps = {
        value: 0,
        valueDisplayFormat: value => value,
        onShiftTabAwait: () => true
    };

    handleIncrease = () => this.onChangeValue(true);

    handleDecrease = () => this.onChangeValue(false);

    onChangeValue = isIncrease => {
        let newValue = this.getChangeValue(isIncrease);
        this.props.onChange(newValue);
    };

    getChangeValue(isIncrease = true) {
        let {value} = this.props;

        if (_.isString(value)) {
            value = parseInt(value);
        }

        if (isIncrease) {
            value = value + 1;
        } else {
            value = value - 1;
        }

        return value;
    }

    handleKeyDownIncreaseButton = e => {
        if (e.key === KeyNames.Tab && e.shiftKey) {
            this.props.onShiftTabAwait();
        }
    };

    render() {
        const {
            value,
            testAutomationId,
            increaseButtonLabel,
            decreaseButtonLabel,
            valueDisplayFormat
        } = this.props;

        return (
            <Block testAutomationId={testAutomationId}>
                <Button
                    testAutomationId="increase"
                    bsStyle="link"
                    block
                    onClick={this.handleIncrease}
                    onKeyDown={this.handleKeyDownIncreaseButton}
                    title={increaseButtonLabel}
                    aria-label={increaseButtonLabel}>
                    <Icon name="chevron-up-big" />
                </Button>
                <div className="text-center time-text">
                    <strong>{valueDisplayFormat(value)}</strong>
                </div>
                <Button
                    testAutomationId="decrease"
                    bsStyle="link"
                    block
                    onClick={this.handleDecrease}
                    title={decreaseButtonLabel}
                    aria-label={decreaseButtonLabel}>
                    <Icon name="chevron-down-big" />
                </Button>
            </Block>
        );
    }
}
