import React from 'react';
import { useStateWithCallbackLazy } from './statehooks';

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({onChange=null,defaultValue=null,selectedValue=null},reducer=null){

    let [ state , setState] = useStateWithCallbackLazy(defaultValue); 

    let onChangeWrapping = React.useCallback((value,event,/*callback*/)=>{
            setState( (oldState)=>{
                return reducer ? reducer(value,actionType) : value
            });
            onChange && onChange(newState,event);
    },[]);

    React.useEffect(()=>{

        if(!defaultValue){

            setState((oldState)=>{
                return reducer ? reducer(selectedValue,actionType) : selectedValue
            });
        }

    },[selectedValue]);

    return [state, onChangeWrapping];

}