import React, { useCallback, useEffect, useRef } from "react";
import { CopySquareOutlined, EditOutlined, PasteSquareOutlined } from "@easyv/react-icons";
import styles from "./ContextMenu.less";

export default function ContextMenu({
  isMultiple,
  menuItem,
  setMenuItem,
  selectedKeys,
  activeKey,
  extraObj,
  onSelectedKeysChange,
  onActiveKeyChange,
  onEditName,
}) {
  const { x, y, chooseKey } = menuItem;
  const { handleEventsToClipboard, handleEventsCopy } = extraObj;
  const ref = useRef(null);
  useEffect(() => {
    const listener = (event) => {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      setMenuItem(null);
    };
    document.addEventListener("click", listener);
    return () => document.removeEventListener("click", listener);
  }, []);

  return (
    <div className={styles.menu} ref={ref} style={{ left: x, top: y }}>
      <div className={styles.menuBox}>
        <ul>
          {isMultiple ? (
            <>
              <li
                onClick={() => {
                  setMenuItem(null);
                  handleEventsToClipboard && handleEventsToClipboard(selectedKeys);
                  onSelectedKeysChange([activeKey]);
                }}
              >
                <CopySquareOutlined className={styles.icon} />
                <span>复制</span>
              </li>
              <li
                onClick={() => {
                  setMenuItem(null);
                  handleEventsCopy && handleEventsCopy(chooseKey);
                  onActiveKeyChange(chooseKey);
                  onSelectedKeysChange([chooseKey]);
                }}
              >
                <PasteSquareOutlined className={styles.icon} />
                <span>粘贴</span>
              </li>
            </>
          ) : null}
          {selectedKeys?.length > 1 ? null : (
            <li
              onClick={() => {
                setMenuItem(null);
                onEditName(chooseKey);
              }}
            >
              <EditOutlined className={styles.icon} />
              <span>重命名</span>
            </li>
          )}
        </ul>
      </div>
    </div>
  );
}
