import type { ProFormColumnsType } from '@ant-design/pro-components';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { type ColProps, Popconfirm } from 'antd';
import type { FormInstance } from 'antd/lib';
import React, { forwardRef, useImperativeHandle } from 'react';

interface PopconfirmFormProps {
  title?: string;
  columns?: ProFormColumnsType[];
  onSubmit?: (values: any) => Promise<boolean>;
  initialValues?: Record<string, any>;
  labelCol?: ColProps;
  wrapperCol?: ColProps;
  children?: React.ReactNode;
}

export interface PopconfirmFormRef {
  open: (data?: Record<string, any>) => void;
  close: () => void;
}

const PopconfirmForm = forwardRef<PopconfirmFormRef, PopconfirmFormProps>(
  (
    {
      labelCol = { span: 4 },
      wrapperCol = { span: 20 },
      columns,
      onSubmit,
      initialValues,
      children,
    },
    ref,
  ) => {
    const [open, setOpen] = React.useState(false);
    const [formData, setFormData] = React.useState(initialValues || {});
    // const [loading, setLoading] = React.useState<boolean>(false);
    // 添加表单实例引用
    const formRef = React.useRef<FormInstance>(null);
    useImperativeHandle(ref, () => ({
      open: (data) => {
        if (data) {
          setFormData(data);
        }
        setOpen(true);
      },
      close: () => setOpen(false),
    }));

    const handleSubmit = async () => {
      try {
        if (onSubmit) {
          await formRef.current?.validateFields();
          // setLoading(true);
          const values = formRef.current?.getFieldsValue();
          const success = await onSubmit(values);
          if (success) {
            setOpen(false);
            return true;
          }
          return false;
        }
        return true;
      } finally {
        // setLoading(false);
      }
    };
    return (
      <Popconfirm
        title={null}
        destroyOnHidden
        icon={null}
        open={open}
        okText="确定"
        cancelText="取消"
        description={
          <BetaSchemaForm
            initialValues={formData}
            layoutType="Form"
            formRef={formRef}
            columns={columns || []}
            layout="horizontal"
            labelCol={labelCol}
            wrapperCol={wrapperCol}
            submitter={false}
          />
        }
        onConfirm={handleSubmit}
        onCancel={() => setOpen(false)}
      >
        {children}
      </Popconfirm>
    );
  },
);

export default React.memo(PopconfirmForm);
