import * as _ from 'lodash';
import * as React from 'react';
import { createContext, ReactNode, useState } from 'react';

interface ModalData {
  /* tslint:disable:no-any */
  component: any;
  /* tslint:disable:no-any */
  props: any;
  onHide: () => void;
}

const noModal: ModalData = {
  component: null,
  props: {},
  onHide: _.noop,
};

export const ModalContext = createContext({
  modal: noModal,
  showModal: _.noop,
  hideModal: _.noop,
});

interface ModalContextProps {
  children: ReactNode;
}
export const ModalContextProvider = ({ children }: ModalContextProps) => {
  const [modal, setModal] = useState(noModal);

  const showModal = (m: ModalData) => {
    setModal(m);
  };
  const hideModal = () => {
    if (modal.onHide) {
      modal.onHide();
    }
    setModal(noModal);
  };

  const contextData = {
    modal,
    showModal,
    hideModal,
  };

  return (
    <ModalContext.Provider value={contextData}>
      {children}
    </ModalContext.Provider>
  );
};

export const ModalRoot = () => {
  const { modal, hideModal } = React.useContext(ModalContext);
  return modal.component ? (
    <modal.component {...modal.props} onRequestClose={hideModal} />
  ) : (
    <></>
  );
};
