import { useState } from "react";
import { Download } from "lucide-react";
import { HttpError } from "../../shared/api/errors";
import type { DocumentSummary } from "../documents/documentTypes";
import { downloadFile } from "./fileState";

export function DownloadButton({ item, onError, onSuccess }: {
  item: DocumentSummary;
  onError: (error: HttpError) => void;
  onSuccess?: () => void;
}) {
  const [pending, setPending] = useState(false);
  const handle = async () => {
    if (pending) return;
    setPending(true);
    try {
      await downloadFile(item.id, `${item.documentName}.${item.fileExtension || "bin"}`);
      onSuccess?.();
    } catch (value) {
      onError(
        value instanceof HttpError
          ? value
          : new HttpError({
              httpStatus: 0,
              code: "INTERNAL_ERROR",
              message: "文件下载失败",
              details: null,
              requestId: "unknown",
              cause: value,
            }),
      );
    } finally {
      setPending(false);
    }
  };
  return (
    <button disabled={pending} onClick={(event) => { event.stopPropagation(); void handle(); }} className="mr-2 text-xs font-black disabled:opacity-50" style={{ color: "#1A5299" }}>
      <Download size={12} className="inline mr-1" />{pending ? "下载中" : "下载"}
    </button>
  );
}
