import React from 'react';
import classNames from 'classnames';
import { noop } from 'node-noop';
import PropTypes from 'prop-types';
import TextField from '@material-ui/core/TextField';
import { withStyles } from '@material-ui/core/styles';
import { Typography } from '@material-ui/core';
import InputAdornment from '@material-ui/core/InputAdornment';

import green from '../../../style/theme/colors/green';

const styles = theme => ({
  input: {
    outline: 'none',
    width: 'inherit',
    '&:focus': {
      border: `1px solid ${green[200]}`
    },
  },
  validationError: {
    position: 'absolute',
    bottom: '0px',
    display: 'block',
    color: 'red'
  },
  inputWrapper: {
    position: 'relative',
    width: '100%',
    paddingBottom: theme.spacing.unit * 3,
    marginBottom: theme.spacing.unit * 1
  }
});
const TextInput = ({
  input,
  InputLabelProps,
  styleSheet,
  select,
  classes,
  required,
  label,
  type,
  multiline,
  meta: { error, visited },
  children,
  readOnly,
  startAdornment,
  endAdornment
}) => (
  <div className={classes.inputWrapper}>
    <TextField
      className={classNames(styleSheet.input, classes.input)}
      {...input}
      required={required}
      InputLabelProps={InputLabelProps}
      select={select}
      error={!!(visited && error)}
      label={label}
      type={type}
      multiline={multiline}
      InputProps={{
        startAdornment: startAdornment ? (
          <InputAdornment position="start">
            {startAdornment}
          </InputAdornment>
        ) : null,
        endAdornment: endAdornment ? (
          <InputAdornment position="end">
            {endAdornment}
          </InputAdornment>
        ) : null,
        readOnly,
      }}
    >
      {children}
    </TextField>
    {visited && error && (
      <span className={classNames(classes.validationError)}>
        <Typography variant="body1" color="inherit">
          {error}
        </Typography>
      </span>
    )}
  </div>
);

TextInput.propTypes = {
  readOnly: PropTypes.bool,
  input: PropTypes.shape({
    name: PropTypes.string,
    onBlur: PropTypes.func,
    onChange: PropTypes.func,
    onDragStart: PropTypes.func,
    onDrop: PropTypes.func,
    onFocus: PropTypes.func,
    value: PropTypes.string
  }),
  styleSheet: PropTypes.shape({
    input: PropTypes.string
  }),
  placeholder: PropTypes.string,
  type: PropTypes.string,
  meta: PropTypes.shape({
    visited: PropTypes.bool,
    error: PropTypes.string
  }),
  children: PropTypes.node
};

TextInput.defaultProps = {
  readOnly: false,
  input: {
    name: '',
    onBlur: noop,
    onChange: noop,
    onDragStart: noop,
    onDrop: noop,
    onFocus: noop,
    value: ''
  },
  styleSheet: { input: 'input' },
  placeholder: '',
  type: 'text',
  meta: {
    visited: false,
    error: undefined
  },
  children: null
};

export default withStyles(styles)(TextInput);
