import { forwardRef, useImperativeHandle, useState, useRef } from "react";
import { Modal, Form, Input, Radio, Button, message, Space } from "antd";
import { useMutation } from "@tanstack/react-query";
import { CreateAudioEncode, UpdateAudioEncode } from "../api/audio";
import type { CreateAudioEncodeReq, AudioEncodeItem } from "../types/audioencode";
import { useGlobal } from "../Context";


interface AddAudioEncodeProps {
  title: string;
  onSuccess: () => void;
}

export interface AddAudioEncodeRef {
  open: (task?: AudioEncodeItem) => void;
}

const AddAudioEncode = forwardRef<AddAudioEncodeRef, AddAudioEncodeProps>(
  ({ title, onSuccess }, ref) => {
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<boolean>(false);
    const [form] = Form.useForm();
    const { ErrorHandle } = useGlobal();
    useImperativeHandle(ref, () => ({
      open: (task?: AudioEncodeItem) => {
        if (task) {
          setEditing(true);
          const formValues = {
            name: task.name,
            id: task.id,
            des: task.des,
          };
          form.setFieldsValue(formValues);
        } else {
          setEditing(false);
          form.resetFields();
          // form.setFieldsValue({
          //   bid: "2",
          // });
        }
        setOpen(true);
      },
    }));

    const { mutate: createMutate, isPending: creating } = useMutation({
      mutationFn: CreateAudioEncode,
      onSuccess: () => {
        message.success("创建任务成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const { mutate: updateMutate, isPending: updating } = useMutation({
      mutationFn: UpdateAudioEncode,
      onSuccess: () => {
        message.success("更新任务成功");
        handleClose();
        onSuccess?.();
      },
      onError: ErrorHandle,
    });

    const handleClose = () => {
      setOpen(false);
      setEditing(false);
      form.resetFields();
    };

    return (
      <Modal
        style={{ top: '-180px' }} // 距离顶部 80px（可改为 10% 等百分比）
        title={title}
  
        open={open}
        onCancel={handleClose}
        centered
        onOk={() => form.submit()}
        confirmLoading={creating || updating}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={(values) => {
            if(creating || updating)return
            console.log(values);

            const { name, des } = values as {
              name: string;
              des: string;
              id?: number;
            };
            const payload: CreateAudioEncodeReq = {
              name,
              des,
            };

            if (editing) {
              const id = (values as any).id;
              updateMutate({ id: String(id), ...payload });
            } else {
              // createMutate(payload);
            }
          }}
        >


          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          <Form.Item
            name="des"
            label="描述"
          >
            <Input placeholder="请输入描述" />
          </Form.Item>
          {editing && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}
        </Form>
      </Modal>
    );
  }
);

export default AddAudioEncode;
