import {ErrorBoundary, Loading, Modal, ModalBtnGroup} from '@components';
import {FC, Suspense} from 'react';
import ReactModal from 'react-modal';
import TreeInfo from './info';
import {ChildrenFC} from '@utils';
import {context, useContextState} from './context';
import {useSubmit, useWatchId} from './hooks';

const modalStyle: ReactModal.Styles = {
  content: {width: '600px', height: '520px'},
};

const TreeModalProvider: ChildrenFC = function({children}) {
  const state = useContextState();
  const {Provider} = context;

  return <Provider value={state}>{children}</Provider>;
};
type Props = {
  id: string;
  onClose: () => void;
  onFetch: () => void;
  visible: boolean;
};

const TreeModal: FC<Props> = function({id, visible, onClose, onFetch}) {
  const [isLoading, onSubmit] = useSubmit({id, onClose, onFetch});
  useWatchId(id, visible);

  return (
    <Modal
      title='菜单权限'
      visible={visible}
      isLoading={isLoading}
      style={modalStyle}
      onSubmit={onSubmit}
      hideBtnGroup
      onClose={onClose}
      testId='role_tree_modal'
    >
      <ErrorBoundary>
        <Suspense fallback={<Loading tip='正在获取菜单' height='200px' />}>
          <TreeInfo />
          <ModalBtnGroup isLoading={isLoading} onClose={onClose} />
        </Suspense>
      </ErrorBoundary>
    </Modal>
  );
};

const TreeModalWrapper: FC<Props> = function(props) {
  return (
    <TreeModalProvider>
      <TreeModal {...props} />
    </TreeModalProvider>
  );
};

export default TreeModalWrapper;
