import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import { t } from 'Framework/i18n';
import Grid from '@material-ui/core/Grid';
import InputBase from '@material-ui/core/InputBase';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import AmountInput from 'App/Shared/Components/AmountInput';
import PropTypes from 'prop-types';

import './Styles.scss';

const styles = () => ({});

class AmountSelection extends React.Component {
    static propTypes = {
        focused: PropTypes.bool,
        disabled: PropTypes.bool,
        onBlur: PropTypes.func,
        onFocus: PropTypes.func,
        onChange: PropTypes.func,
        value: PropTypes.number,
        amountLabel: PropTypes.string,
    };

    state = {
        focused: false,
    };

    componentDidUpdate(prevProps) {
        const { focused, disabled } = this.props;
        if (!disabled && prevProps.focused !== focused) {
            this.setState({ focused });
        }
    }

    onBlur = (...args) => {
        const { disabled, onBlur } = this.props;
        if (!disabled) {
            this.setState({ focused: false });
            onBlur && onBlur(...args);
        }
    };

    onFocus = (...args) => {
        const { disabled, onFocus } = this.props;
        if (!disabled) {
            this.setState({ focused: true });
            onFocus && onFocus(...args);
        }
    };

    render() {
        const { onChange, value, amountLabel } = this.props;

        return (
            <Grid item xs={12}>
                <div className="amount-selection-input-container">
                    {this.state.focused ? (
                        <AmountInput
                            value={value}
                            onChange={onChange}
                            onBlur={this.onBlur}
                            amountLabel={amountLabel}
                            autoFocus
                        />
                    ) : (
                        <Typography variant="body1" component="div" onFocus={this.onFocus}>
                            <InputBase readOnly value={t('amountSelection.total', { value: value })} />
                        </Typography>
                    )}
                </div>
                <Divider />
            </Grid>
        );
    }
}

export default withStyles(styles, { name: 'AmountSelection' })(AmountSelection);
