import { useEffect, useRef, useState } from "react";
import { Graph, Node } from "@antv/x6";
import img from "@/assets/wf_icon_handle.gif";
import { MenuProps } from "antd";
import Port from "./Port";
import Content from "./Content";

export default ({ node, graph }: { node: Node; graph: Graph }) => {
  const ref = useRef<HTMLDivElement>(null);
  const { width, height } = node.getSize();
  const [hovered, setHovered] = useState(false);
  const [isSelected, setIsSelected] = useState(false);

  const items: MenuProps["items"] = [
    { key: "copy", label: "复制" },
    { key: "delete", label: "删除" },
  ];

  useEffect(() => {
    const { offsetWidth = 0, offsetHeight = 0 } = ref.current || {};
    if (offsetHeight !== height || offsetWidth !== width) {
      node.resize(offsetWidth, offsetHeight);
    }
  }, []);

  graph?.on("selection:changed", (args) => {
    setIsSelected(graph.isSelected(node));
  });

  return (
    <div
      className="flow-node text-14px relative"
      style={{ borderColor: isSelected || hovered ? "#0e52e0" : "#d9d9d9" }}
      ref={ref}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <Content
        img={img}
        node={node}
        graph={graph}
        items={items}
        headerStyle={{
          backgroundImage:
            "linear-gradient(to bottom, rgba(32, 139, 226, 0.2), #ffffff)",
        }}
      />

      <Port hovered={hovered} style={{ right: -7, cursor: "crosshair" }} />
    </div>
  );
};
