import React, { useState } from 'react';
const actionType = "@SET_SELECTED";
/**
 * Inspired from https://react-spectrum.adobe.com/react-stately/index.html
 * Common state management
 * this hook is used for easily manage the controller and uncontrolled the selections of form component.
 * We can use it for Radio, DropDown, Tab components
 * props name should be onChange,defaultValue,selectedValue.
 * @param {*} props = onChange,defaultValue,selectedValue
 */

export default function useSelectionControl(_ref) {
  let {
    onChange = null,
    defaultValue = null,
    selectedValue = null
  } = _ref;
  let reducer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  let [state, setState] = useState(defaultValue);
  let onChangeWrapping = React.useCallback((value, event
  /*callback*/
  ) => {
    setState(oldState => {
      return reducer ? reducer(value, actionType) : value;
    });
    onChange && onChange(value, event);
  }, [onChange]);
  React.useEffect(() => {
    if (!defaultValue) {
      setState(oldState => {
        return reducer ? reducer(selectedValue, actionType) : selectedValue;
      });
    }
  }, [selectedValue]);
  return [state, onChangeWrapping];
}