"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";
import { createPortal } from "react-dom";
import type { MindMapNode } from "./mindmapTypes";

// 菜单项配置
interface ContextMenuItem {
  key?: string;
  label?: string;
  shortcut?: string;
  danger?: boolean;
  disabled?: boolean;
  divider?: boolean;
  show?: (node: MindMapNode | null) => boolean;
}

// 节点右键菜单配置
const NODE_MENU_ITEMS: ContextMenuItem[] = [
  {
    key: "INSERT_NODE",
    label: "插入同级节点",
    shortcut: "Enter",
  },
  {
    key: "INSERT_CHILD_NODE",
    label: "插入子级节点",
    shortcut: "Tab",
  },
  {
    key: "INSERT_PARENT_NODE",
    label: "插入父节点",
    shortcut: "Shift + Tab",
  },
  {
    key: "ADD_GENERALIZATION",
    label: "插入概要",
    shortcut: "Ctrl + G",
  },
  { divider: true },
  {
    key: "UP_NODE",
    label: "上移节点",
    shortcut: "Ctrl + ↑",
  },
  {
    key: "DOWN_NODE",
    label: "下移节点",
    shortcut: "Ctrl + ↓",
  },
  {
    key: "UNEXPAND_ALL",
    label: "收起所有下级节点",
  },
  {
    key: "EXPAND_ALL",
    label: "展开所有下级节点",
  },
  { divider: true },
  {
    key: "REMOVE_NODE",
    label: "删除节点",
    shortcut: "Delete",
    danger: true,
  },
  {
    key: "REMOVE_CURRENT_NODE",
    label: "仅删除当前节点",
    shortcut: "Shift + Backspace",
    danger: true,
  },
  { divider: true },
  {
    key: "COPY_NODE",
    label: "复制节点",
    shortcut: "Ctrl + C",
  },
  {
    key: "CUT_NODE",
    label: "剪切节点",
    shortcut: "Ctrl + X",
  },
  {
    key: "PASTE_NODE",
    label: "粘贴节点",
    shortcut: "Ctrl + V",
  },
  { divider: true },
  {
    key: "REMOVE_HYPERLINK",
    label: "移除超链接",
    show: (node) => !!node?.getData?.("hyperlink"),
  },
  {
    key: "REMOVE_NOTE",
    label: "移除备注",
    show: (node) => !!node?.getData?.("note"),
  },
  {
    key: "REMOVE_CUSTOM_STYLES",
    label: "一键去除自定义样式",
  },
  {
    key: "EXPORT_CUR_NODE_TO_PNG",
    label: "导出该节点为图片",
  },
  { divider: true },
  {
    key: "AI_CONTINUE",
    label: "AI续写",
  },
];

interface MindmapContextMenuProps {
  mindmap: any | null;
}

export function MindmapContextMenu({ mindmap }: MindmapContextMenuProps) {
  const [visible, setVisible] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [targetNode, setTargetNode] = useState<MindMapNode | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const requestShowRef = useRef<{ x: number; y: number; node: MindMapNode } | null>(null);

  // 判断是否禁用某个菜单项
  const isItemDisabled = useCallback(
    (item: ContextMenuItem): boolean => {
      if (!targetNode) return false;

      const isRoot = (targetNode as any).isRoot === true;
      const isGeneralization = (targetNode as any).isGeneralization === true;

      switch (item.key) {
        case "INSERT_NODE":
        case "INSERT_PARENT_NODE":
        case "ADD_GENERALIZATION":
          return isRoot || isGeneralization;

        case "INSERT_CHILD_NODE":
          return isGeneralization;

        case "COPY_NODE":
        case "CUT_NODE":
          return isGeneralization;

        case "UP_NODE": {
          if (isRoot || isGeneralization) return true;
          const parent = (targetNode as any).parent;
          if (!parent || !Array.isArray(parent.children)) return true;
          return parent.children.findIndex((item: unknown) => item === targetNode) === 0;
        }

        case "DOWN_NODE": {
          if (isRoot || isGeneralization) return true;
          const parent = (targetNode as any).parent;
          if (!parent || !Array.isArray(parent.children)) return true;
          const children = parent.children;
          return children.findIndex((item: unknown) => item === targetNode) === children.length - 1;
        }

        default:
          return false;
      }
    },
    [targetNode]
  );

  // 过滤显示的菜单项
  const getVisibleItems = useCallback((): ContextMenuItem[] => {
    return NODE_MENU_ITEMS.filter((item) => {
      if (item.divider) return true;
      if (item.show && !item.show(targetNode)) return false;
      return true;
    });
  }, [targetNode]);

  // 隐藏菜单
  const hide = useCallback(() => {
    setVisible(false);
    setTargetNode(null);
    setPosition({ x: -9999, y: -9999 });
    requestShowRef.current = null;
  }, []);

  // 执行命令
  const executeCommand = useCallback(
    (key: string) => {
      if (!mindmap || !targetNode) return;

      switch (key) {
        case "COPY_NODE":
          mindmap.renderer?.copy?.();
          break;
        case "CUT_NODE":
          mindmap.renderer?.cut?.();
          break;
        case "PASTE_NODE":
          mindmap.renderer?.paste?.();
          break;
        case "REMOVE_HYPERLINK":
          if (typeof (targetNode as any).setHyperlink === "function") {
            (targetNode as any).setHyperlink("", "");
          }
          break;
        case "REMOVE_NOTE":
          if (typeof (targetNode as any).setNote === "function") {
            (targetNode as any).setNote("");
          }
          break;
        case "EXPORT_CUR_NODE_TO_PNG": {
          const getTextFromHtml = (html: string) => {
            const div = document.createElement("div");
            div.innerHTML = html;
            return div.textContent || div.innerText || "";
          };
          const nodeText = targetNode.getData?.("text") || "";
          mindmap.doExport?.export("png", true, getTextFromHtml(String(nodeText)), false, targetNode);
          break;
        }
        case "UNEXPAND_ALL":
          mindmap.execCommand?.(key, false, targetNode);
          break;
        case "EXPAND_ALL":
          mindmap.execCommand?.(key, (targetNode as any).uid || "");
          break;
        case "AI_CONTINUE":
          // 触发 AI 续写
          if (typeof window !== "undefined") {
            window.dispatchEvent(
              new CustomEvent("mindmap-ai-continue", {
                detail: { node: targetNode },
              })
            );
          }
          break;
        default:
          mindmap.execCommand?.(key);
          break;
      }

      hide();
    },
    [hide, mindmap, targetNode]
  );

  // 显示菜单 - 使用 requestAnimationFrame 确保 DOM 更新后再显示
  const show = useCallback((x: number, y: number, node: MindMapNode) => {
    setTargetNode(node);

    // 计算可见菜单项数量
    const visibleItems = NODE_MENU_ITEMS.filter((item) => {
      if (item.divider) return true;
      if (item.show && !item.show(node)) return false;
      return true;
    });

    // 计算实际菜单高度（每个菜单项约40px，分隔符约10px）
    const itemHeight = 40;
    const dividerHeight = 10;
    const estimatedHeight = visibleItems.reduce((acc, item) => {
      return acc + (item.divider ? dividerHeight : itemHeight);
    }, 0) + 16; // +16 是上下 padding

    const menuWidth = 250;
    const menuHeight = estimatedHeight + 20; // 额外的安全边距

    // 初始位置：鼠标右侧下方
    let posX = x + 10;
    let posY = y + 10;

    // 如果右侧空间不足，显示在左侧
    if (posX + menuWidth > window.innerWidth) {
      posX = x - menuWidth - 20;
    }

    // 如果下方空间不足，固定到窗口底部（与参考实现一致）
    if (posY + menuHeight > window.innerHeight) {
      posY = window.innerHeight - menuHeight - 10;
    }

    // 确保不会超出左边界
    if (posX < 10) {
      posX = 10;
    }

    // 确保菜单顶部不会超出窗口
    if (posY < 10) {
      posY = 10;
    }

    setPosition({ x: posX, y: posY });
    setVisible(true);
  }, []);

  // 监听右键事件
  useEffect(() => {
    if (!mindmap) return;

    const handleContextMenu = (e: Event) => {
      const mouseEvent = e as MouseEvent;

      // 检查是否点击在节点上
      const target = mouseEvent.target as HTMLElement | SVGElement;

      // simple-mind-map 的节点结构
      // 尝试多种选择器
      const nodeSelectors = [
        ".smm-node",           // 主节点容器
        ".smm-node-light",     // 亮色主题节点
        "g[role='node']",      // 带 role 属性的 g 元素
        "g.smooth-smooth",     // 特定样式的 g 元素
      ];

      let clickedNodeEl: Element | null = null;
      for (const selector of nodeSelectors) {
        clickedNodeEl = target.closest?.(selector) || null;
        if (clickedNodeEl) break;
      }

      // 如果没找到节点选择器，尝试查找包含 text 的元素
      if (!clickedNodeEl) {
        const parent = target.parentElement;
        if (parent) {
          // 检查父元素是否包含文本内容
          const textContainer = parent.querySelector("text");
          if (textContainer) {
            clickedNodeEl = parent;
          }
        }
      }

      if (!clickedNodeEl) return;

      // 阻止默认右键菜单
      mouseEvent.preventDefault();
      mouseEvent.stopPropagation();

      // 获取当前激活的节点作为右键点击的节点
      const renderer = mindmap.renderer;
      if (!renderer) return;

      // 使用 activeNodeList 或 lastActiveNodeList
      const activeList = renderer.activeNodeList ?? [];
      const lastActiveList = renderer.lastActiveNodeList ?? [];

      const node = (activeList[0] ?? lastActiveList[0] ?? null) as MindMapNode | null;

      if (node) {
        show(mouseEvent.clientX, mouseEvent.clientY, node);
      }
    };

    // 延迟查找容器，确保 DOM 已经渲染
    const timer = setTimeout(() => {
      const container = document.querySelector("[data-testid='mindmap-canvas']");
      if (container) {
        container.addEventListener("contextmenu", handleContextMenu, true);
      }
    }, 100);

    return () => {
      clearTimeout(timer);
      const container = document.querySelector("[data-testid='mindmap-canvas']");
      if (container) {
        container.removeEventListener("contextmenu", handleContextMenu, true);
      }
    };
  }, [mindmap, show]);

  // 监听画布点击事件隐藏菜单
  useEffect(() => {
    if (!mindmap) return;

    const hideMenu = () => {
      hide();
    };

    mindmap.on?.("draw_click", hideMenu);
    mindmap.on?.("node_click", hideMenu);
    mindmap.on?.("expand_btn_click", hideMenu);

    return () => {
      mindmap.off?.("draw_click", hideMenu);
      mindmap.off?.("node_click", hideMenu);
      mindmap.off?.("expand_btn_click", hideMenu);
    };
  }, [mindmap, hide]);

  // 点击外部隐藏菜单
  useEffect(() => {
    if (!visible) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        hide();
      }
    };

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        hide();
      }
    };

    const handleScroll = () => {
      hide();
    };

    const handleResize = () => {
      hide();
    };

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleEscape);
    document.addEventListener("scroll", handleScroll, true);
    window.addEventListener("resize", handleResize);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
      document.removeEventListener("scroll", handleScroll, true);
      window.removeEventListener("resize", handleResize);
    };
  }, [visible, hide]);

  // 渲染菜单
  const renderMenu = () => {
    const visibleItems = getVisibleItems();

    return (
      <div
        ref={menuRef}
        className="mindmap-contextmenu"
        style={{
          position: "fixed",
          left: `${position.x}px`,
          top: `${position.y}px`,
          zIndex: 9999,
          minWidth: "200px",
          maxWidth: "280px",
          background: "#ffffff",
          borderRadius: "8px",
          boxShadow: "0 4px 16px rgba(0, 0, 0, 0.15)",
          padding: "8px 0",
          fontSize: "14px",
          fontFamily:
            "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
        }}
        onContextMenu={(e) => {
          e.preventDefault();
        }}
      >
        {visibleItems.map((item, index) => {
          if (item.divider) {
            return (
              <div
                key={`divider-${index}`}
                style={{
                  height: "1px",
                  background: "#e5e7eb",
                  margin: "4px 12px",
                }}
              />
            );
          }

          const disabled = isItemDisabled(item);

          return (
            <div
              key={item.key || `item-${index}`}
              onClick={() => {
                if (disabled) return;
                if (!item.key) return;
                executeCommand(item.key);
              }}
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                padding: "8px 16px",
                cursor: disabled ? "not-allowed" : "pointer",
                color: item.danger ? "#ef4444" : disabled ? "#9ca3af" : "#1f2937",
                background: "transparent",
                transition: "background 0.1s",
              }}
              onMouseEnter={(e) => {
                if (!disabled) {
                  e.currentTarget.style.background = "#f3f4f6";
                }
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "transparent";
              }}
            >
              <span style={{ fontSize: "14px" }}>{item.label || ""}</span>
              {item.shortcut && (
                <span
                  style={{
                    fontSize: "12px",
                    color: "#9ca3af",
                    marginLeft: "24px",
                  }}
                >
                  {item.shortcut}
                </span>
              )}
            </div>
          );
        })}
      </div>
    );
  };

  if (typeof document === "undefined" || !visible) {
    return null;
  }

  return createPortal(renderMenu(), document.body);
}
