import { FormPageFooter, MemoSpinLoding } from "@/components";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
} from "@dage/pc-components";
import { DatePicker, Form, FormInstance } from "antd";
import { useCallback, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function BannerCreateOrEditPage() {
  const formRef = useRef<FormInstance>(null);
  const navigate = useNavigate();
  const params = useParams();
  const [loading, setLoading] = useState(false);

  const handleCancel = useCallback(() => {
    navigate(-1);
  }, [navigate]);

  const handleSubmit = useCallback(async () => {
    if (!(await formRef.current?.validateFields())) return;

    const { banner = [], ...rest } = formRef.current?.getFieldsValue();

    if (params.id) {
      rest.id = params.id;
    }

    handleCancel();
  }, [handleCancel, params]);

  return (
    <div style={{ position: "relative" }}>
      {loading && <MemoSpinLoding />}
      <DageUploadProvider>
        <DageUploadConsumer>
          {(data) => (
            <>
              <Form ref={formRef} labelCol={{ span: 2 }}>
                <Form.Item
                  label="海报"
                  name="banner"
                  rules={[{ required: true, message: "请上传海报" }]}
                >
                  <DageUpload
                    tips="支持png、jpg和jpeg格式；最多1张，最大20M"
                    action={
                      process.env.REACT_APP_API_URL + "/api/cms/history/upload"
                    }
                    maxSize={20}
                    maxCount={1}
                  />
                </Form.Item>

                <Form.Item
                  label="发布日期"
                  name="date"
                  rules={[{ required: true, message: "请选择日期" }]}
                >
                  <DatePicker className="w220" />
                </Form.Item>
              </Form>

              {!loading && (
                <FormPageFooter
                  disabled={data?.uploading}
                  onSubmit={handleSubmit}
                  onCancel={handleCancel}
                />
              )}
            </>
          )}
        </DageUploadConsumer>
      </DageUploadProvider>
    </div>
  );
}
