import { datasetApi } from "@/api/dataset";
import {
  Button,
  Divider,
  Flex,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Select,
  Space,
  Tooltip,
} from "antd";
import React, { useEffect } from "react";

// 生成简短的UUID
const generateShortUUID = () => {
  return Math.random().toString(36).substring(2, 8);
};

interface CreateTaskModalProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (values: any) => void; // 修改onConfirm的类型以接收表单值
  datasetList: { id: number; name: string; description: string }[] | undefined;
  taskTypeOptions?: { value: string; label: string }[];
  onDatasetCreate?: () => void;
}

const CreateTaskModal: React.FC<CreateTaskModalProps> = ({
  visible,
  onCancel,
  onConfirm,
  datasetList,
  taskTypeOptions,
  onDatasetCreate
}) => {
  const [form] = Form.useForm();
  const [datasetName, setDatasetName] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  // 监听表单字段变化，自动生成数据集名称
  useEffect(() => {
    const simulator = form.getFieldValue('simulator');
    const taskType = form.getFieldValue('task_type');
    const camera = form.getFieldValue('camera');
    
    if (simulator && taskType && camera) {
      const uuid = generateShortUUID();
      const generatedName = `${simulator}-${taskType}-${camera}-${uuid}`;
      setDatasetName(generatedName);
    }
  }, [form]);

  // 监听表单字段变化
  const handleFormChange = () => {
    const taskType = form.getFieldValue('task_type');
    const camera = form.getFieldValue('camera');
    
    if (taskType && camera) {
      const uuid = generateShortUUID();
      const generatedName = `${taskType}-${camera}-${uuid}`;
      setDatasetName(generatedName);
    }
  };
  const simulationOptions = [
    { value: "robotwin", label: "robotwin" },
  ];
  const cameraTypeOptions = [
    { value: "D435", label: "D435" },
    { value: "D515", label: "D515" },
  ];

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onConfirm(values);
      form.resetFields(); // 提交成功后重置表单
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  const handleCreateDataset = async () => {
    setLoading(true);
    try {
      await datasetApi.createDataset({
        name: datasetName,
      });
      message.success("创建数据集成功");
      setLoading(false);
      setDatasetName("");
      onDatasetCreate?.();
    } catch (error) {
      setLoading(false);
      message.error("创建数据集失败");
    }
  };

  return (
    <Modal
      title="创建生成任务"
      closable={false}
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      destroyOnHidden
    >
      <Form form={form} layout="vertical" onValuesChange={handleFormChange}>
        <Form.Item
          label="仿真器"
          name="simulator"
          rules={[{ required: true, message: "请选择仿真器!" }]}
        >
          <Select placeholder="请选择仿真器" options={simulationOptions}>
          </Select>
        </Form.Item>
        <Form.Item
          label="任务类型"
          name="task_type"
          rules={[{ required: true, message: "请选择任务类型!" }]}
        >
          <Select placeholder="请选择任务类型" options={taskTypeOptions}>
          </Select>
        </Form.Item>
        <Form.Item
          label="相机类型"
          name="camera"
          rules={[{ required: true, message: "请选择相机类型!" }]}
        >
          <Select placeholder="请选择相机类型" options={cameraTypeOptions}>
          </Select>
        </Form.Item>
        <Form.Item
          label="轨迹条数"
          name="trajectory_count"
          rules={[{ required: true, message: "请输入轨迹条数!" }]}
        >
          <InputNumber
            min={1}
            max={10000}
            style={{ width: "100%" }}
            placeholder="请输入轨迹条数 (1-10000)"
          />
        </Form.Item>
        <Form.Item label="任务名称" name="task_name">
          <Input placeholder="请输入任务名称（可选）" />
        </Form.Item>
        <Form.Item
          label="数据集"
          name="dataset_id"
          rules={[{ required: true, message: "请录入数据集" }]}
        >
          <Select
            placeholder="请选择数据集"
            popupRender={(menu) => (
              <div>
                {menu}
                <Divider style={{ margin: "8px 0" }} />
                <Flex
                  style={{ width: "100%" }}
                  gap={16}
                  justify="space-between"
                >
                  <Input
                    onChange={(e) => {
                      e.stopPropagation();
                      setDatasetName(e.target.value);
                    }}
                    value={datasetName}
                    placeholder="请输入数据集名称"
                    disabled={loading}
                  />
                  <Button
                    type="primary"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleCreateDataset();
                    }}
                    disabled={loading}
                  >
                    创建
                  </Button>
                </Flex>
              </div>
            )}
          >
            {datasetList?.map((item) => (
              <Select.Option
                key={item.id}
                value={item.id}
                title={item.description}
              >
                {item.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateTaskModal;
