import { useEffect, useState } from "react";
import { Button, Form, message, Modal, Upload, UploadFile } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import {
  downloadKnowledgeItemFileUsingGet,
  replaceKnowledgeItemFileUsingPut,
  uploadKnowledgeItemsUsingPost,
} from "../knowledge-management.api";
import {
  KnowledgeContentType,
  KnowledgeItem,
  KnowledgeSourceType,
} from "../knowledge-management.model";

export default function KnowledgeItemEditor({
  open,
  setId,
  data,
  parentPrefix,
  onCancel,
  onSuccess,
  readOnly,
}: {
  open: boolean;
  setId: string;
  data?: Partial<KnowledgeItem> | null;
  parentPrefix?: string;
  readOnly?: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}) {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [replaceFileList, setReplaceFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);
  const isFileItem =
    data?.contentType === KnowledgeContentType.FILE ||
    data?.sourceType === KnowledgeSourceType.FILE_UPLOAD;
  const isCreateMode = !data?.id;

  useEffect(() => {
    setFileList([]);
    setReplaceFileList([]);
  }, [open, data?.id]);

  const handleFileBeforeUpload = (file: File) => {
    setFileList((prev) => [
      ...prev,
      {
        uid: `${Date.now()}-${file.name}`,
        name: file.name,
        status: "done",
        originFileObj: file,
      },
    ]);
    return false;
  };

  const handleFileRemove = (removedFile: UploadFile) => {
    setFileList((prev) => prev.filter((file) => file.uid !== removedFile.uid));
    return true;
  };

  const handleReplaceFileBeforeUpload = (file: File) => {
    setReplaceFileList([
      {
        uid: `${Date.now()}-${file.name}`,
        name: file.name,
        status: "done",
        originFileObj: file,
      },
    ]);
    message.success("已选择替换文件，提交后生效");
    return false;
  };

  const handleReplaceFileRemove = (removedFile: UploadFile) => {
    setReplaceFileList((prev) => prev.filter((file) => file.uid !== removedFile.uid));
    return true;
  };

  const handleDownloadFile = async () => {
    if (!data?.id) {
      return;
    }
    try {
      await downloadKnowledgeItemFileUsingGet(setId, data.id, data.sourceFileId);
    } catch (error) {
      console.error("下载文件失败", error);
      message.error("下载失败，请稍后重试");
    }
  };

  const handleSubmit = async () => {
    try {
      if (isCreateMode) {
        if (fileList.length === 0) {
          message.warning("请先选择文件");
          return;
        }
        setLoading(true);
        const formData = new FormData();
        fileList.forEach((file) => {
          const origin = file.originFileObj as File | undefined;
          if (origin) {
            formData.append("files", origin);
          }
        });
        if (parentPrefix) {
          formData.append("parentPrefix", parentPrefix);
        }
        await uploadKnowledgeItemsUsingPost(setId, formData);
        message.success(`已创建 ${fileList.length} 个知识条目`);
      } else {
        if (!data?.id) {
          return;
        }
        if (!isFileItem) {
          message.info("该条目非文件类型，无需替换文件");
          return;
        }
        if (replaceFileList.length === 0) {
          message.warning("请先选择要替换的文件");
          return;
        }
        const replaceFile = replaceFileList[0]?.originFileObj as File | undefined;
        if (!replaceFile) {
          message.warning("请先选择要替换的文件");
          return;
        }
        setLoading(true);
        const formData = new FormData();
        formData.append("file", replaceFile);
        await replaceKnowledgeItemFileUsingPut(setId, data.id, formData);
        message.success("知识条目更新成功");
      }

      setFileList([]);
      setReplaceFileList([]);
      onSuccess();
    } catch {
      message.error("操作失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const title = data?.id ? "编辑知识条目" : "新建知识条目";

  return (
    <Modal
      title={title}
      open={open}
      onCancel={onCancel}
      onOk={handleSubmit}
      okText="确定"
      cancelText="取消"
      width={860}
      maskClosable={false}
      okButtonProps={{ disabled: readOnly }}
      confirmLoading={loading}
    >
      <Form layout="vertical" disabled={readOnly}>
        {isCreateMode && (
          <Form.Item label="上传文件" required>
            <Upload
              beforeUpload={handleFileBeforeUpload}
              fileList={fileList}
              multiple
              onRemove={handleFileRemove}
              showUploadList={{ showPreviewIcon: false }}
              disabled={readOnly}
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <div className="text-xs text-gray-500 mt-1">
              支持多格式文件；多文件将自动拆分为多个条目
            </div>
          </Form.Item>
        )}
        {!isCreateMode && isFileItem && (
          <Form.Item label="文件">
            <div className="flex items-center gap-2">
              <span className="truncate" title={data?.sourceFileId || "-"}>
                {data?.sourceFileId || "-"}
              </span>
              <Button size="small" onClick={handleDownloadFile} disabled={readOnly}>
                下载
              </Button>
            </div>
          </Form.Item>
        )}
        {!isCreateMode && isFileItem && !readOnly && (
          <Form.Item label="替换文件">
            <Upload
              beforeUpload={handleReplaceFileBeforeUpload}
              fileList={replaceFileList}
              onRemove={handleReplaceFileRemove}
              showUploadList={{ showPreviewIcon: false }}
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <div className="text-xs text-gray-500 mt-1">仅支持单文件</div>
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
}
