import { FormPageFooter, MemoSpinLoding } from "@/components";
import { Button, DatePicker, Form, FormInstance, Input, Select } from "antd";
import { useCallback, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { TopicDrawer } from "../components/topicDrawer";

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

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

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

    const { ...rest } = formRef.current?.getFieldsValue();

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

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

  const handleAddTopic = () => {
    setDrawerVisible(true);
  };

  const handleCloseDrawer = () => {
    setDrawerVisible(false);
  };

  return (
    <div style={{ position: "relative" }}>
      {loading && <MemoSpinLoding />}

      <Form ref={formRef} labelCol={{ span: 2 }}>
        <Form.Item
          label="标题"
          name="title"
          rules={[{ required: true, message: "请输入内容" }]}
        >
          <Input
            className="w220"
            placeholder="请输入内容，最多20字"
            maxLength={20}
            showCount
          />
        </Form.Item>

        <Form.Item
          label="摘要"
          name="content"
          rules={[{ required: true, message: "请输入内容" }]}
        >
          <Input.TextArea
            className="w450"
            placeholder="请输入内容，最多200字"
            maxLength={200}
            showCount
            rows={6}
          />
        </Form.Item>

        <Form.Item
          label="题目"
          name="content"
          rules={[{ required: true, message: "请新增题目" }]}
        >
          <Button type="primary" onClick={handleAddTopic}>
            新增
          </Button>
        </Form.Item>

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

        <Form.Item label="展示状态" name="type">
          <Select
            defaultValue="lucy"
            style={{ width: 220 }}
            options={[
              { value: "jack", label: "Jack" },
              { value: "lucy", label: "Lucy" },
              { value: "Yiminghe", label: "yiminghe" },
              { value: "disabled", label: "Disabled", disabled: true },
            ]}
          />
        </Form.Item>
      </Form>

      {!loading && (
        <FormPageFooter onSubmit={handleSubmit} onCancel={handleCancel} />
      )}

      <TopicDrawer open={drawerVisible} close={handleCloseDrawer} />
    </div>
  );
}
