import { useEffect, useRef, useState } from "react";
import { Download, FileWarning, RefreshCw, X } from "lucide-react";
import { HttpError } from "../../shared/api/errors";
import { AllowedAction } from "../../shared/api/enums";
import type { DocumentSummary } from "../documents/documentTypes";
import {
  createPreviewUrl,
  downloadFile,
  acquirePreview,
  revokeObjectUrl,
} from "./fileState";

function errorText(error: HttpError): string {
  if (error.code === "PREVIEW_UNAVAILABLE") return "当前文件类型暂不支持在线查看";
  if (error.code === "FILE_NOT_FOUND") return "文件不存在";
  if (error.code === "DOCUMENT_VIEW_FORBIDDEN" || error.httpStatus === 403) {
    return "当前账号无权查看该文件";
  }
  return error.message;
}

export function FilePreviewModal({ item, onClose }: {
  item: DocumentSummary;
  onClose: () => void;
}) {
  const [url, setUrl] = useState<string | null>(null);
  const [error, setError] = useState<HttpError | null>(null);
  const [loading, setLoading] = useState(true);
  const [downloading, setDownloading] = useState(false);
  const mounted = useRef(true);
  const canDownload = item.allowedActions.includes(AllowedAction.DOWNLOAD);

  useEffect(() => {
    mounted.current = true;
    const preview = acquirePreview(item.id);
    let ownedUrl: string | null = null;
    setLoading(true);
    setError(null);
    void preview.promise
      .then((result) => {
        if (!mounted.current) return;
        if (!result.contentType?.toLowerCase().includes("application/pdf")) {
          throw new HttpError({
            httpStatus: result.httpStatus,
            code: "INTERNAL_ERROR",
            message: "文件内容无法查看",
            details: null,
            requestId: result.requestId,
          });
        }
        ownedUrl = createPreviewUrl(result.blob);
        setUrl(ownedUrl);
      })
      .catch((value: unknown) => {
        if (!mounted.current) return;
        setError(
          value instanceof HttpError
            ? value
            : new HttpError({
                httpStatus: 0,
                code: "INTERNAL_ERROR",
                message: "文件查看失败",
                details: null,
                requestId: "unknown",
                cause: value,
              }),
        );
      })
      .finally(() => {
        if (mounted.current) setLoading(false);
      });
    return () => {
      mounted.current = false;
      preview.release();
      revokeObjectUrl(ownedUrl);
    };
  }, [item.id]);

  const download = async () => {
    if (downloading || !canDownload) return;
    setDownloading(true);
    try {
      await downloadFile(item.id, `${item.documentName}.${item.fileExtension || "bin"}`);
    } catch (value) {
      setError(value instanceof HttpError ? value : null);
    } finally {
      setDownloading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center" style={{ background: "rgba(26,82,153,.55)" }} onClick={onClose}>
      <div className="w-[900px] h-[86vh] flex flex-col bg-white shadow-2xl" onClick={(event) => event.stopPropagation()}>
        <div className="h-11 px-5 flex items-center justify-between text-white" style={{ background: "#1A5299" }}>
          <span className="font-black">文件查看 · {item.documentName}</span>
          <button onClick={onClose}><X size={17} /></button>
        </div>
        <div className="flex-1 min-h-0 flex items-center justify-center" style={{ background: "#EBF4FD" }}>
          {loading && <div className="font-bold" style={{ color: "#1A5299" }}><RefreshCw className="inline animate-spin mr-2" size={16} />正在加载文件…</div>}
          {url && <iframe title={`${item.documentName} PDF查看`} src={url} className="w-full h-full border-0" />}
          {error && (
            <div className="text-center p-8" style={{ color: "#1A5299" }}>
              <FileWarning size={40} className="mx-auto mb-3 opacity-60" />
              <div className="font-black">{errorText(error)}</div>
              {error.requestId && <div className="text-xs font-bold opacity-55 mt-2">错误编号：{error.requestId}</div>}
              {canDownload && (
                <button disabled={downloading} onClick={() => void download()} className="mt-5 px-4 py-2 text-sm font-black text-white disabled:opacity-60" style={{ background: "#3191eb" }}>
                  <Download size={14} className="inline mr-2" />{downloading ? "正在下载…" : "下载原始文件"}
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
