import { Button, Col, Form, message, Row, Space, Spin } from "antd";
import FormItemsRenderer from "./FormItemsRenderer";

/**
 * 表单构建器组件
 */
const FormBuilder = (props) => {
  const {
    values,
    options,
    gutter = 24,
    span = 12,
    labelCol = { span: 4 },
    useAutoGenerateRequired = true,
    showActionButtons = true,
    submitButtonText = "提交",
    cancelButtonText = "取消",
    showSubmitButton = true,
    showCancelButton = true,
    customActionButtons,
    extraActionButtons,
    loading = false,
    ...restProps
  } = props;

  const handleCancel = () => {
    window.history.back();
  };

  return (
    <Spin spinning={loading}>
      <Form
        labelCol={labelCol}
        scrollToFirstError
        wrapperCol={{ span: 24 - labelCol.span }}
        initialValues={values}
        onFinishFailed={() => {
          message.error("请补全必填项");
        }}
        style={{ width: `calc(100% - ${gutter * 2}px)`, margin: `0 auto` }}
        {...restProps}
      >
        <Row gutter={gutter}>
          <FormItemsRenderer
            options={options}
            labelCol={labelCol}
            span={span}
            gutter={gutter}
            useAutoGenerateRequired={useAutoGenerateRequired}
            initialValues={values}
          />
        </Row>
        {showActionButtons && (
          <Row gutter={gutter} style={{ marginTop: 24 }}>
            <Col span={24} style={{ textAlign: "center" }}>
              {customActionButtons || (
                <Space>
                  {showSubmitButton && (
                    <Button type="primary" htmlType="submit">
                      {submitButtonText}
                    </Button>
                  )}
                  {extraActionButtons}
                  {showCancelButton && (
                    <Button onClick={handleCancel}>
                      {cancelButtonText}
                    </Button>
                  )}
                </Space>
              )}
            </Col>
          </Row>
        )}
      </Form>
    </Spin>
  );
};

FormBuilder.displayName = "FormBuilder";

export default FormBuilder;
