// @flow
import { useState, useCallback } from 'react';

export type UseExpanderChildCallback = (
  callback: () => void,
  dependencies: [],
) => () => void;

export type UseExpanderState = (
  initialIsOpen: boolean,
) => [boolean, (isOpen: boolean) => void, UseExpanderChildCallback];

/**
 * @description Optional hook to handle basic cases of the Expander component
 *
 * @param {boolean} initalIsOpen Whether the expander should default to open or not.
 *
 * @returns Returns an array of three items:
 *    1. Boolean state for wether the expander is open or not.
 *    2. A setter function for the boolean state.
 *    3. A custom useCallback hook that will set expander state to false before calling it's given callback.
 */
export const useExpanderState: UseExpanderState = (initalIsOpen) => {
  const [isOpen, setIsOpen] = useState<boolean>(initalIsOpen);

  const useExpanderChildCallback: UseExpanderChildCallback = (
    callback,
    dependencies,
  ) =>
    useCallback(() => {
      setIsOpen(false);
      callback();
    }, [callback, ...dependencies]);

  return [isOpen, setIsOpen, useExpanderChildCallback];
};
