import React from 'react';
import DateTime from 'react-datetime';
import 'react-datetime/css/react-datetime.css';
import omit from 'lodash/omit';
import styles from './datepicker-input.scss'; // eslint-disable-line no-unused-vars
import FieldControl from '../FieldControl';

function getInputProps(props) {
  const { input, ...resultProps } = props;
  return { ...resultProps, ...input };
}

const propTypes = {};

const defaultProps = {};

/**
 * Text Input
 *
 */
class DatepickerInput extends React.PureComponent {
  onChange = value => {
    const { onChange } = getInputProps(this.props);
    if (onChange && typeof value === 'object') {
      onChange(value.toString());
    } else {
      onChange(value);
    }
  };

  onFocus = () => {
    const { onFocus, value } = getInputProps(this.props);
    if (onFocus) {
      onFocus(value);
    }
  };

  onBlur = () => {
    const { onBlur, value } = getInputProps(this.props);
    if (onBlur) {
      onBlur(value);
    }
  };

  render() {
    return (
      <FieldControl length={length} {...this.props}>
        {restProps => {
          const { value, ...dateProps } = getInputProps(restProps);
          const valueDate = new Date(value);
          return (
            <DateTime
              styleName="styles.input-control"
              onChange={this.onChange}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              dateFormat="YYYY/MM/DD"
              timeFormat=""
              value={valueDate.toUTCString() === 'Invalid Date' ? value : valueDate}
              {...omit(dateProps, ['onChange', 'onFocus', 'onBlur'])}
            />
          );
        }}
      </FieldControl>
    );
  }
}

DatepickerInput.propTypes = propTypes;
DatepickerInput.defaultProps = defaultProps;
export default DatepickerInput;
