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

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}
      onSubmit={onSubmit}
      onClose={onClose}
      testId='role_tree_modal'
    >
      <ErrorBoundary>
        <Suspense fallback={<Loading tip='正在获取菜单' height='200px' />}>
          <TreeInfo />
        </Suspense>
      </ErrorBoundary>
    </Modal>
  );
};

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

export default TreeModalWrapper;
