import { useState } from "react";
import { Button, Form, Modal, message, Select } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import DatasetFileTransfer from "@/components/business/DatasetFileTransfer";
import { Dataset, DatasetFile } from "@/pages/DataManagement/dataset.model";
import {
  importKnowledgeItemsUsingPost,
} from "../knowledge-management.api";
import { knowledgeStatusOptions } from "../knowledge-management.const";
import { KnowledgeStatusType } from "../knowledge-management.model";

export default function ImportKnowledgeItemsDialog({
  setId,
  onImported,
  disabled,
}: {
  setId: string;
  onImported: () => void;
  disabled?: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [selectedFilesMap, setSelectedFilesMap] = useState<Record<string, DatasetFile>>({});
  const [selectedDataset, setSelectedDataset] = useState<Dataset | null>(null);

  const handleSubmit = async () => {
    if (!selectedDataset) {
      message.warning("请先选择数据集");
      return;
    }
    const fileIds = Object.keys(selectedFilesMap);
    if (fileIds.length === 0) {
      message.warning("请至少选择一个文件");
      return;
    }

    const values = await form.validateFields();

    try {
      await importKnowledgeItemsUsingPost(setId, {
        datasetId: selectedDataset.id,
        fileIds,
        status: values.status || undefined,
      });
      message.success("导入成功");
      setOpen(false);
      setSelectedFilesMap({});
      setSelectedDataset(null);
      form.resetFields();
      onImported();
    } catch {
      message.error("导入失败，请重试");
    }
  };

  return (
    <>
      <Button
        icon={<PlusOutlined />}
        onClick={() => {
          form.resetFields();
          form.setFieldsValue({ status: KnowledgeStatusType.DRAFT });
          setOpen(true);
        }}
        disabled={disabled}
      >
        导入数据集文件
      </Button>
      <Modal
        title="导入数据集文件"
        open={open}
        onCancel={() => {
          setOpen(false);
          setSelectedFilesMap({});
          setSelectedDataset(null);
        }}
        onOk={handleSubmit}
        okText="确定"
        cancelText="取消"
        width={1000}
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="条目状态" name="status">
            <Select options={knowledgeStatusOptions} />
          </Form.Item>
        </Form>
        <DatasetFileTransfer
          open={open}
          selectedFilesMap={selectedFilesMap}
          onSelectedFilesChange={setSelectedFilesMap}
          onDatasetSelect={setSelectedDataset}
        />
      </Modal>
    </>
  );
}
