import React from 'react';
import { Input } from 'semantic-ui-react';

/**
 * Creates an SUI `<Input>` component managed via form context
 * Should be called with Context containing (at least) the following:
 *  - the `name` field
 *  - a `handleChange()` method to receive new values
 * @param {string} displayName - Display name for the returned component.
 * @param {Object} Context - Form context.
 * @param {string} name - State variable for this field.
 * @param {Object} extraProps - Extra props to add to the element.
 * @returns {Object} component
 */
const createInputComponent = (displayName, Context, name, extraProps = { }) => {
  const Component = (props) => (
    <Context.Consumer>
      { (state) => {
        /**
         * Handles changes to the input field
         * Sends these to the form as well as any `onChange` handler.
         * Note that `event.preventDefault()` is not supported.
         * Ideally this would be a class method, but Enzyme doesn't yet support
         * the `contextType` API so we wouldn't be able to test it.
         * @param {Array<any>} params - Event parameters.
         * @returns {void}
         */
        const handleChange = (...params) => {
          state.handleChange(...params);

          const { onChange } = props;
          if (onChange) {
            onChange(...params);
          }
        };

        return (
          <Input
            { ...props }
            name={ name }
            onChange={ handleChange }
            value={ state[name] }
            { ...extraProps }
          />
        );
      } }
    </Context.Consumer>
  );

  Component.displayName = displayName;
  Component.propTypes = Input.propTypes;

  return Component;
};

export default createInputComponent;
