import { Dispatch, SetStateAction, useCallback, useEffect, useState } from "react";

/**
 * Helper hook to coordinate state handling between internal and external.
 * @param defaultValue Default value of state
 * @param value Getter for external state management
 * @param setValue Setter for external state management
 * @returns Consolidated useState
 */
export function useExposableState<T>(
  defaultValue: T,
  value?: T,
  setValue?: Dispatch<SetStateAction<T>>,
): [T, Dispatch<SetStateAction<T>>] {
  const [state, setState] = useState<T>(value ?? defaultValue);

  /** Toggle state externally */
  useEffect(() => {
    if(value !== undefined) {
        setState(value);
    }
  }, [value]);

  //Setter for internal components
  const setter : Dispatch<SetStateAction<T>> =  useCallback((action: SetStateAction<T>) => {
    setState(action);
    setValue?.(action);
  }, []);

  return [state, setter];
}
