import React from 'react';
import PropTypes from 'prop-types';
import './text-input.scss';
import FieldControl from '../FieldControl';
import { getInputProps } from '../_helpers/tools';

const propTypes = {
  value: PropTypes.string,
  prefix: PropTypes.string,
  input: PropTypes.object
};

const defaultProps = {
  value: '',
  prefix: '',
  input: null
};

/**
 * Text Input
 *
 */
class TextInput extends React.PureComponent {
  render() {
    const {
      prefix,
      ...props
    } = this.props;
    const { value } = props.input || props;
    const length = typeof value === 'string' ? value.length : 0;
    return (
      <FieldControl length={length} {...props}>
        {restProps => {
          const inputResult = (
            <input
              styleName="input-control"
              {...getInputProps(restProps)}
            />
          );
          return prefix ? (
            <div styleName="input-group">
              {prefix && <span styleName="input-group-addon"> {prefix} </span>}
              {inputResult}
            </div>
          ) : inputResult;
        }}
      </FieldControl>
    );
  }
}

TextInput.propTypes = propTypes;
TextInput.defaultProps = defaultProps;
export default TextInput;
