import { Dropdown, type MenuProps } from "antd";
import { proxy, useSnapshot, ref } from "valtio";

export type DropdownItem = NonNullable<MenuProps["items"]>[number] & {
  onClick: () => void;
};

const defaultProps = {
  isOpen: false,
  menu: {
    items: ref([]) as DropdownItem[],
  },
  x: 0,
  y: 0,
};

const localStore = proxy(defaultProps);

/** 想让下拉菜单全局唯一 */
export const CardDropdown: React.FC = () => {
  const { isOpen, menu, x, y } = useSnapshot(localStore);
  return (
    <Dropdown
      open
      menu={menu as any}
      overlayStyle={{
        position: "fixed",
        left: "50%",
        top: "50%",
        transform: `translate(-50%, -100%) translate3d(${x}px, ${y}px, 0)`,
        opacity: isOpen ? 1 : 0, // 不能直接用在open属性上，否则会造成渲染不及时的问题
      }}
      placement="top"
      autoAdjustOverflow={false}
      arrow
    >
      <div style={{ width: 0, height: 0 }} />
    </Dropdown>
  );
};

export function showCardDropdown(props: {
  items: DropdownItem[];
  x: number;
  y: number;
}) {
  localStore.x = props.x;
  localStore.y = props.y;
  localStore.menu = {
    items: props.items.map((x) => {
      const tmpOnClick = x.onClick;
      x.onClick = () => {
        tmpOnClick();
        localStore.isOpen = false;
      };
      return x;
    }),
  };
  localStore.isOpen = true;
}

export function hideCardDropdown() {
  localStore.isOpen = false;
}

// 全局点击收起
document.addEventListener("click", () => {
  localStore.isOpen = false;
});
