import {
  cancelUploadUsingPut,
  preUploadUsingPost,
  uploadFileChunkUsingPost,
} from "@/pages/DataManagement/dataset.api";
import { Button, Empty, Progress, Tag } from "antd";
import { DeleteOutlined, FileTextOutlined } from "@ant-design/icons";
import { useEffect } from "react";
import { useFileSliceUpload } from "@/hooks/useSliceUpload";

export default function TaskUpload() {
  const { createTask, taskList, removeTask, handleUpload, registerStreamUploadListener } = useFileSliceUpload(
    {
      preUpload: preUploadUsingPost,
      uploadChunk: uploadFileChunkUsingPost,
      cancelUpload: cancelUploadUsingPut,
    },
    true, // showTaskCenter
    true  // enableStreamUpload
  );

  useEffect(() => {
    const uploadHandler = (e: Event) => {
      const customEvent = e as CustomEvent;
      console.log('[TaskUpload] Received upload event detail:', customEvent.detail);
      const { files } = customEvent.detail;
      const task = createTask(customEvent.detail);
      console.log('[TaskUpload] Created task with prefix:', task.prefix);
      handleUpload({ task, files });
    };
    window.addEventListener("upload:dataset", uploadHandler);
    return () => {
      window.removeEventListener("upload:dataset", uploadHandler);
    };
  }, [createTask, handleUpload]);

  // 注册流式上传监听器
  useEffect(() => {
    const unregister = registerStreamUploadListener();
    return unregister;
  }, [registerStreamUploadListener]);

  return (
    <div
      className="w-90 max-w-90 max-h-96 overflow-y-auto p-2"
      id="header-task-popover"
    >
      {taskList.length > 0 &&
        taskList.map((task) => (
          <div key={task.key} className="border-b border-gray-200 pb-2">
            <div className="flex items-center justify-between">
              <div>{task.title}</div>
              <Button
                type="text"
                danger
                disabled={!task?.cancelFn}
                onClick={() =>
                  removeTask({
                    ...task,
                    isCancel: true,
                  })
                }
                icon={<DeleteOutlined />}
              ></Button>
            </div>

            <Progress size="small" percent={Number(task.percent)} />
            {task.streamUploadInfo && (
              <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                <Tag icon={<FileTextOutlined />} size="small">
                  按行分割
                </Tag>
                <span>
                  已上传: {task.streamUploadInfo.uploadedLines} 行
                </span>
                {task.streamUploadInfo.totalFiles > 1 && (
                  <span>
                    ({task.streamUploadInfo.fileIndex}/{task.streamUploadInfo.totalFiles} 文件)
                  </span>
                )}
              </div>
            )}
          </div>
        ))}
      {taskList.length === 0 && (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无上传任务"
        />
      )}
    </div>
  );
}
