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

export default ({ node, graph }: { node: Node; graph: Graph }) => {
  const [hovered, setHovered] = useState(false);
  const [isSelected, setIsSelected] = useState(false);
  const { icon, color, style, port, type, } = node.getData();

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

  return (
    <div
      className="flow-node"
      style={{
        boxShadow: isSelected ? "0 0 0 8px #2941701a" : "",
        ...style,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <Content
        img={
          <i className={"iconfont " + icon} style={{ fontSize: 60, color }} />
        }
        node={node}
        graph={graph}
        selected={isSelected}
        hovered={hovered}
      />

      {!!port.in && (
        <Port
          hovered={hovered}
          out={false}
          style={{ left: -7, cursor: "default" }}
          node={node}
          graph={graph}
        />
      )}
      {new Array(port.out).fill("").map((item, index) => (
        <Port
          key={index}
          hovered={hovered}
          style={{
            right: -7,
            cursor: "crosshair",
            top: (100 / (port.out + 1)) * (index + 1),
          }}
          node={node}
          graph={graph}
        />
      ))}
      {type && (
        <div style={{position: 'absolute', bottom: -10, left: 'calc(50% - 8px)', width: 16, height: 16}}>
          <Port
            hovered={hovered}
            type='extra'
            style={{
              cursor: "default",
            }}
            node={node}
            graph={graph}
          />
        </div>
      )}
    </div>
  );
};
