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,
  label: PropTypes.node,
  onChange: PropTypes.func,
  placeholder: PropTypes.string,
  /**
   * Object of props passed to the <textarea> element
   */
  textareaProps: PropTypes.object,
};

const defaultProps = {
  children: null,
  disabled: false,
  groupProps: {},
  helper: null,
  label: null,
  onChange: () => {},
  placeholder: null,
  textareaProps: {},
};

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

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

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

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

  const handleChange = (event) => {
    const value = event.currentTarget.value.trim();
    setValue(value);
    onChange(value);
  };

  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}
    >
      <textarea
        className="sui-a-form-control"
        disabled={disabled}
        placeholder={placeholder}
        defaultValue={getValue() || ''}
        onChange={handleChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        {...textareaProps}
      />
      {children}
    </FormGroup>
  );
};

FieldTextareaUI.propTypes = propTypes;
FieldTextareaUI.defaultProps = defaultProps;

export const FieldTextarea = withFormsy(FieldTextareaUI);
