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

const style: ReactModal.Styles = {
  content: {
    width: '540px',
    height: '680px',
  },
};

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

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

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

export default GoodsModal;
