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

const modalStyle: ReacatModal.Styles = {
  content: {width: '460px', height: '300px'},
};

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

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

  return (
    <ModalComponent
      visible={visible}
      style={modalStyle}
      title={`${isEdit ? '修改' : '新增'}部门`}
      onClose={onClose}
      onSubmit={onSubmit}
      isLoading={isLoading}
      testId='department_modal'
      hideBtnGroup
    >
      <FormProvider {...formInstance}>
        <ErrorBoundary>
          <Suspense fallback={<Loading tip='正在获取部门信息' />}>
            <Info id={id} />
            <ModalBtnGroup onClose={onClose} isLoading={isLoading} />
          </Suspense>
        </ErrorBoundary>
      </FormProvider>
    </ModalComponent>

  );
};

export default Modal;
