import React from 'react';
import PropTypes from 'prop-types';
import { withFormsy, propTypes as formsyPropTypes } from 'formsy-react';
import { FormGroup } from '../../core/molecules/formGroup/FormGroup';

const propTypes = {
  ...formsyPropTypes,
  children: PropTypes.node,
  disabled: PropTypes.bool,
  /**
   * Object of props passed to the <FormGroup> component
   */
  groupProps: PropTypes.object,
  helper: PropTypes.node,
  /**
   * Object of props passed to the <input> element
   */
  inputProps: PropTypes.object,
  label: PropTypes.node,
  onChange: PropTypes.func,
  placeholder: PropTypes.string,
  type: PropTypes.string,
  trimValue: PropTypes.bool,
};

const defaultProps = {
  children: null,
  disabled: false,
  groupProps: {},
  helper: null,
  inputProps: {},
  label: null,
  onChange: () => {},
  placeholder: null,
  type: 'text',
  trimValue: true,
};

export const FieldInputUI = ({
  // Formsy props
  getErrorMessage,
  getValue,
  isFormSubmitted,
  isPristine,
  isRequired,
  isValid,
  setValue,

  // Global props
  children,
  disabled,
  groupProps,
  helper,
  label,
  onChange,
  placeholder,
  trimValue,

  // Custom props
  inputProps,
  type,
}) => {
  const [isTouched, setIsTouched] = React.useState(false);
  const [isFocused, setIsFocused] = React.useState(false);

  const isFeedbackVisible = (isTouched && !isPristine()) || isFormSubmitted();
  const isError = !isValid() && isFeedbackVisible;

  const handleChange = (event) => {
    let valueTarget = event.currentTarget.value;
    if (trimValue === true) {
      valueTarget = valueTarget.trim();
    }
    setValue(valueTarget);
    onChange(valueTarget);
  };

  const handleFocus = () => {
    setIsFocused(true);
    setIsTouched(true);
  };

  const handleBlur = () => {
    setIsFocused(false);
  };

  return (
    <FormGroup
      label={label}
      helper={helper}
      isOptional={!isRequired()}
      validationState={!isFocused && isError ? 'danger' : null}
      feedbackMessage={isFeedbackVisible && getErrorMessage()}
      {...groupProps}
    >
      <input
        className="sui-a-form-control"
        type={type}
        disabled={disabled}
        placeholder={placeholder}
        defaultValue={getValue() || ''}
        onChange={handleChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        {...inputProps}
      />
      {children}
    </FormGroup>
  );
};

FieldInputUI.propTypes = propTypes;
FieldInputUI.defaultProps = defaultProps;

export const FieldInput = withFormsy(FieldInputUI);
