"use client";

import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";

type EditorMode = "view" | "edit";

const loadScript = (src: string) =>
  new Promise<void>((resolve, reject) => {
    const existing = document.querySelector(`script[src="${src}"]`);
    if (existing) {
      existing.addEventListener("load", () => resolve(), { once: true });
      resolve();
      return;
    }
    const script = document.createElement("script");
    script.src = src;
    script.async = true;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`加载 ONLYOFFICE 脚本失败: ${src}`));
    document.body.appendChild(script);
  });

const hashKey = (input: string) => {
  let hash = 0;
  for (let i = 0; i < input.length; i += 1) {
    hash = (hash << 5) - hash + input.charCodeAt(i);
    hash |= 0;
  }
  return Math.abs(hash).toString();
};

const docTypeFromExt = (ext: string) => {
  const word = ["doc", "docx", "odt", "rtf"];
  const slide = ["ppt", "pptx", "odp"];
  const sheet = ["xls", "xlsx", "ods", "csv"];
  if (word.includes(ext)) return "text";
  if (slide.includes(ext)) return "presentation";
  if (sheet.includes(ext)) return "spreadsheet";
  return "text";
};

export default function OnlyOfficePage() {
  const params = useSearchParams();
  const fileUrl = params.get("fileUrl") ?? "";
  const fileName = params.get("fileName") ?? "未命名文档";
  const fileType = (params.get("fileType") ?? "docx").toLowerCase();
  const mode = (params.get("mode") ?? "edit") as EditorMode;
  const [error, setError] = useState<string | null>(null);
  const baseUrl = process.env.NEXT_PUBLIC_ONLYOFFICE_BASE_URL;
  const storageHostOverride =
    process.env.NEXT_PUBLIC_ONLYOFFICE_STORAGE_HOST_OVERRIDE;

  const targetDocType = useMemo(() => docTypeFromExt(fileType), [fileType]);
  const resolvedFileUrl = useMemo(() => {
    if (!fileUrl) return "";
    try {
      const u = new URL(fileUrl);
      if (
        storageHostOverride &&
        (u.hostname === "127.0.0.1" ||
          u.hostname === "localhost" ||
          u.hostname === "host.docker.internal")
      ) {
        u.hostname = storageHostOverride;
      }
      return u.toString();
    } catch {
      return fileUrl;
    }
  }, [fileUrl, storageHostOverride]);

  useEffect(() => {
    if (!baseUrl) {
      setError("缺少 NEXT_PUBLIC_ONLYOFFICE_BASE_URL 配置，无法加载编辑器。");
      return;
    }
    if (!fileUrl) {
      setError("缺少 fileUrl 参数。");
      return;
    }
    const scriptUrl = `${baseUrl.replace(/\/$/, "")}/web-apps/apps/api/documents/api.js`;
    loadScript(scriptUrl)
      .then(() => {
        // @ts-expect-error ONLYOFFICE 全局对象
        if (!window.DocsAPI) {
          throw new Error("未检测到 DocsAPI，请检查 ONLYOFFICE 版本。");
        }
        // eslint-disable-next-line new-cap,@typescript-eslint/no-explicit-any
        new (window as any).DocsAPI.DocEditor("onlyoffice-frame", {
          width: "100%",
          height: "100%",
          document: {
            fileType,
            title: fileName,
            url: resolvedFileUrl,
            key: hashKey(`${resolvedFileUrl}-${fileName}`),
          },
          documentType: targetDocType,
          editorConfig: {
            mode: mode === "view" ? "view" : "edit",
            lang: "zh-CN",
            customization: {
              feedback: { visible: false },
            },
          },
        });
      })
      .catch((err: Error) => {
        setError(err.message);
      });
  }, [baseUrl, fileName, fileType, mode, resolvedFileUrl, targetDocType]);

  if (error) {
    return (
      <div className="flex h-screen flex-col items-center justify-center gap-3 bg-slate-50">
        <p className="text-base font-semibold text-red-600">ONLYOFFICE 加载失败</p>
        <p className="text-sm text-gray-600">{error}</p>
      </div>
    );
  }

  return <div id="onlyoffice-frame" className="h-screen w-screen bg-slate-50" />;
}
