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

const style: ReactModalStyle = {
  content: {
    width: '560px',
    height: '500px',
  },
};

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

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

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

export default MenuModal;
