import React, { useEffect, useRef, useState } from "react";
import { PlasoContentType } from "../config/url";

interface PlasoViewerProps {
  url: string;
  token: string;
  type: PlasoContentType;
  devTools?: boolean;
  onError?: (error: Error) => void;
}

interface WebViewElement extends HTMLElement {
  executeJavaScript: (code: string) => Promise<void>;
  addEventListener: (event: string, callback: (event: any) => void) => void;
  removeEventListener: (event: string, callback: (event: any) => void) => void;
}

// 检测是否在Electron环境中
const isElectronEnvironment = (): boolean => {
  // 检查是否存在Electron特有的对象
  return (
    !!(window as any).process?.type ||
    !!(window as any).electron ||
    !!(window as any).require?.("electron")
  );
};

// 检测是否支持webview
const isWebViewSupported = (): boolean => {
  // 首先检查是否在Electron环境中
  if (!isElectronEnvironment()) {
    return false;
  }

  try {
    // 在Electron环境中，检查webview元素是否有特殊属性
    const webview = document.createElement("webview");
    return typeof (webview as any).executeJavaScript === "function";
  } catch (e) {
    return false;
  }
};

export const PlasoViewer: React.FC<PlasoViewerProps> = ({
  url,
  token,
  type,
  devTools,
  onError,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const webviewRef = useRef<WebViewElement | null>(null);
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
  const [useWebView, setUseWebView] = useState<boolean>(false);

  const handleError = (error: Error) => {
    setError(error);
    if (onError) {
      onError(error);
    }
  };

  useEffect(() => {
    if (!containerRef.current) {
      console.warn("Container ref is not available yet");
      return;
    }

    // 检测是否支持webview
    const webViewSupported = isWebViewSupported();
    setUseWebView(webViewSupported);
    console.log(
      `环境检测: ${isElectronEnvironment() ? "Electron环境" : "非Electron环境"}`
    );
    console.log(`WebView支持状态: ${webViewSupported ? "支持" : "不支持"}`);

    if (webViewSupported) {
      setupWebView();
    } else {
      setupIframe();
    }

    // 清理函数
    return () => {
      cleanup();
    };
  }, [url, token, type, onError]);

  const setupWebView = async () => {
    try {
      setIsLoading(true);
      setError(null);

      // 创建一个新的webview元素
      const webview = document.createElement("webview") as WebViewElement;
      webview.setAttribute("src", url);
      webview.setAttribute("style", "width: 100%; height: 100%; border: none;");
      webview.setAttribute("allowpopups", "true");
      webview.setAttribute("nodeintegration", "true");
      webview.setAttribute(
        "webpreferences",
        "contextIsolation=no,nodeIntegration=yes,webSecurity=no"
      );

      webview.setAttribute("allowRunningInsecureContent", "true");
      webview.setAttribute("websecurity", "false");

      webview.setAttribute("allow", "file://*");
      webview.setAttribute("devTools", "yes");

      // webview.setAttribute("allowFileAccess", "true");

      webview.addEventListener("dom-ready", () => {
        const { ipcRenderer } = window.require("electron");
        // @ts-ignore
        ipcRenderer.send("enable-remote", webview.getWebContentsId()); // 激活webview的remote功能‌:ml-citation{ref="1,3" data="citationList"}

        // 打开开发者工具
        if (devTools) {
          // @ts-ignore
          webview.openDevTools();
        }
      });

      // webview.addEventListener("did-finish-load", () => {
      //   // 强制 reload，忽略缓存
      //   webview.reloadIgnoringCache();
      // });

      // 处理webview加载错误
      const handleLoadError = (error: any) => {
        handleError(
          new Error(`WebView加载失败: ${error.message || "未知错误"}`)
        );
        setIsLoading(false);
      };

      // 处理webview加载完成
      const handleLoadComplete = () => {
        console.log("webview加载完成");
        setIsLoading(false);
      };

      webview.addEventListener("did-finish-load", handleLoadComplete);
      webview.addEventListener("did-fail-load", handleLoadError);

      // 将webview添加到容器中
      containerRef.current!.appendChild(webview);
      webviewRef.current = webview;
    } catch (err) {
      handleError(err instanceof Error ? err : new Error("设置WebView失败"));
      setIsLoading(false);
      // 如果webview设置失败，尝试使用iframe
      setupIframe();
    }
  };

  const setupIframe = () => {
    try {
      setIsLoading(true);
      setError(null);

      // 创建一个新的iframe元素
      const iframe = document.createElement("iframe");
      iframe.setAttribute("nodeintegration", "yes");
      iframe.setAttribute(
        "webpreferences",
        "nodeIntegration=yes, contextIsolation=no, webSecurity=no"
      );

      iframe.setAttribute("websecurity", "false");
      iframe.src = url;
      iframe.style.width = "100%";
      iframe.style.height = "100%";
      iframe.style.border = "none";
      iframe.style.overflow = "hidden";

      // 处理iframe加载错误
      const handleIframeError = () => {
        handleError(new Error("iframe加载失败"));
        setIsLoading(false);
      };

      // 处理iframe加载完成
      const handleIframeLoad = () => {
        setIsLoading(false);
      };

      iframe.addEventListener("load", handleIframeLoad);
      iframe.addEventListener("error", handleIframeError);

      // 将iframe添加到容器中
      containerRef.current!.appendChild(iframe);
      iframeRef.current = iframe;
    } catch (err) {
      handleError(err instanceof Error ? err : new Error("设置iframe失败"));
      setIsLoading(false);
    }
  };

  const cleanup = () => {
    if (containerRef.current) {
      if (webviewRef.current) {
        containerRef.current.removeChild(webviewRef.current);
        webviewRef.current = null;
      }
      if (iframeRef.current) {
        containerRef.current.removeChild(iframeRef.current);
        iframeRef.current = null;
      }
    }
  };

  if (error) {
    return (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          color: "red",
        }}
      >
        错误: {error.message}
      </div>
    );
  }

  return (
    <div
      ref={containerRef}
      style={{
        width: "100%",
        height: "100%",
        position: "relative",
        overflow: "hidden",
      }}
    />
  );
};
