/* eslint-disable no-prototype-builtins */
import { useMemoizedFn, useUpdate } from 'ahooks';
import { useMemo, useRef } from 'react';

function useControllableEventValue() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var defaultValue = options.defaultValue,
      _options$defaultValue = options.defaultValuePropName,
      defaultValuePropName = _options$defaultValue === void 0 ? 'defaultValue' : _options$defaultValue,
      _options$valuePropNam = options.valuePropName,
      valuePropName = _options$valuePropNam === void 0 ? 'value' : _options$valuePropNam,
      _options$trigger = options.trigger,
      trigger = _options$trigger === void 0 ? 'onChange' : _options$trigger;
  var value = props[valuePropName];
  var isControlled = props.hasOwnProperty(valuePropName);
  var initialValue = useMemo(function () {
    if (isControlled) {
      return value;
    }

    if (props.hasOwnProperty(defaultValuePropName)) {
      return props[defaultValuePropName];
    }

    return defaultValue;
  }, []);
  var stateRef = useRef(initialValue);

  if (isControlled) {
    stateRef.current = value;
  }

  var update = useUpdate();

  function setState(event) {
    if (!isControlled) {
      stateRef.current = event.target[valuePropName];
      update();
    }

    if (props[trigger]) {
      props[trigger](event);
    }
  }

  return [stateRef.current, useMemoizedFn(setState)];
}

export default useControllableEventValue;