import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm } from '@ant-design/pro-form';

export const EmptyReconfirmProps: ReconfirmProps = {
  title: '',
  message: '',
  comfirmHandler: async () => {},
  onSubmitting: async () => {},
  onSuccess: async () => {},
  onError: async () => {},
};

export type ReconfirmProps = {
  title: string;
  message: string;
  comfirmHandler: () => Promise<any>;
  onSubmitting: () => Promise<any>;
  onSuccess: (params: any) => Promise<void>;
  onError: (params: any, error: unknown) => Promise<void>;
};

export type ReconfirmFormProps = {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  reconfirmProps: ReconfirmProps;
};

const ReconfirmForm: React.FC<ReconfirmFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  return (
    <ModalForm
      formRef={formRef}
      title={props.reconfirmProps.title}
      width="600px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue({
            type: 'all',
          });
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const params = await props.reconfirmProps.onSubmitting();
        try {
          await props.reconfirmProps.comfirmHandler();
          await props.reconfirmProps.onSuccess(params);
        } catch (error) {
          await props.reconfirmProps.onError(params, error);
        }
      }}
    >
      <div>{props.reconfirmProps.message}</div>
    </ModalForm>
  );
};

export default ReconfirmForm;
