import React, { useEffect, useState } from 'react';
import { Modal } from './Modal';

export interface ModalComponentProps {
  /**
   * Callback to close the modal.
   */
  closeModal: () => void;
}

export interface UseModalResult {
  /**
   * The component for the modal. (Make sure to add this to the DOM)
   */
  ModalWrapper: React.FC;
  /**
   * Method to close the modal.
   */
  closeModal: () => void;
  /**
   * Method to open the modal.
   */
  openModal: () => void;
  /**
   * Indicates whether the modal is shown or not.
   */
  isShown: boolean;
}

/**
 * Wraps the given component in a `Modal` and returns methods to control the visibility of the modal.
 * @param Component The component that should be shown as modal.
 */
export const useModal = (
  Component: React.ComponentType<ModalComponentProps>,
): UseModalResult => {
  const [isShown, setIsShown] = useState<boolean>(false);

  const closeModal = (): void => setIsShown(false);
  const openModal = (): void => setIsShown(true);

  const ModalWrapper: React.FC = () => {
    // This State + Effect is used to force a re render which the animation library listens to.
    const [innerShown, setInnerShown] = useState<boolean>(false);

    useEffect(() => {
      setInnerShown(isShown);
    }, []);

    return (
      <Modal isShown={innerShown} onBackDropClicked={closeModal}>
        <Component closeModal={closeModal} />
      </Modal>
    );
  };

  return {
    ModalWrapper,
    closeModal,
    openModal,
    isShown,
  };
};
