import { useStateWithCallbackLazy } from "./statehooks";
import { useEffectCallOnlyAfterState } from "./useEffectCallonlyAfterState";
import { useCallback } from "react";

const actionType = "@HANDLE_INPUT_TEXT"

/**
 * props name should be onChange,defaultValue,value.
 * @param {*} props = onChange,defaultValue,value
 */
export default ({ defaultValue = '', value: propsValue, onChange }, reducer=null)=>{

    const [ value , setValue] = useStateWithCallbackLazy(propsValue || defaultValue); 
    
    useEffectCallOnlyAfterState(() => {  /* Reset the local state when controlled component*/
        if (!defaultValue) {
          setValue((oldState)=>{
            return reducer ? reducer(propsValue,actionType) : propsValue
          });
        }
      }, [propsValue]);


    const onChangeWrapping = useCallback((event) => {
        let inputValue= event.target.value;

        !defaultValue && setValue( (prevValue)=>{
          return reducer ? reducer(inputValue,actionType) : inputValue
        });
          
        onChange && onChange(inputValue, event);
      },[onChange]
    );

    return { value, onChangeWrapping };
}