import React from 'react';
import { Modal, Form } from 'antd';
import { ModalProps } from 'antd/es/modal';
import { FormProps, FormInstance } from 'antd/es/form';

export interface FormModalProps extends ModalProps {
  onSubmit?: (from: FormInstance) => void;
  formProps?: FormProps;
  form?: FormInstance;
}

const FormModal: React.FC<FormModalProps> = (props) => {
  const { children, onSubmit, formProps = {}, onCancel, visible, form, ...rest } = props;

  const realForm = form ?? Form.useForm()[0];
  const handleSubmit = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault();
    onSubmit?.(realForm);
  };

  const renderChildren = (form: FormInstance) => {
    if (typeof children === 'function') {
      return children(form);
    } else {
      return children;
    }
  };
  return (
    <Modal onOk={handleSubmit} onCancel={onCancel} visible={visible} {...rest}>
      <Form form={realForm} {...formProps}>
        {renderChildren(realForm)}
      </Form>
    </Modal>
  );
};

export default FormModal;
