import {ErrorBoundary, Loading, Modal, ModalBtnGroup} from '@components';
import {FC, Suspense} from 'react';
import ReactModal from 'react-modal';
import {useFormState} from './hooks';
import {FormProvider} from 'react-hook-form';
import Info from './Info';

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

type Props = {
  visible: boolean,
  onClose: () => void,
  onFetch: () => void,
  id: string,
};

const RoleModal: FC<Props> = function({visible, onClose, onFetch, id}) {
  const [{isLoading, formInstance}, {onSubmit}] = useFormState({visible, onFetch, onClose, id});

  return (
    <Modal
      visible={visible}
      style={modalStyle}
      title={`${id ? '修改' : '新增'}角色`}
      onClose={onClose}
      isLoading={isLoading}
      onSubmit={onSubmit}
      testId='role_modal'
      hideBtnGroup
    >
      <FormProvider {...formInstance}>
        <ErrorBoundary>
          <Suspense fallback={<Loading tip='正在获取角色信息' />}>
            <Info id={id} />
            <ModalBtnGroup isLoading={isLoading} onClose={onClose} />
          </Suspense>
        </ErrorBoundary>
      </FormProvider>
    </Modal>
  );
};

export default RoleModal;
