import { useEffect, useRef } from "react";
import { Dnd } from "@antv/x6-plugin-dnd";
import { useModel } from "umi";
import { nodeItems } from "@/components/nodes";

export default function index() {
  const containerRef = useRef(null);
  const { graph, mode } = useModel("flowModel");
  const dnd = useRef<Dnd>();

  useEffect(() => {
    if (graph && containerRef.current) {
      dnd.current = new Dnd({
        target: graph,
        scaled: false,
        dndContainer: containerRef.current,
      });
    }
  }, [graph, containerRef.current]);

  const onStartDrag = (
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
    node: any
  ) => {
    if (!graph || !dnd.current) return;

    const n = graph?.createNode({
      shape: node.name,
      data: {
        type: node.key,
        name: node.text,
      },
    });

    dnd.current?.start(n, e.nativeEvent);
  };

  return (
    mode === "edit" && (
      <div
        ref={containerRef}
        className="absolute left-32px top-32px z-2 flex gap-12px box-shadow rounded-12px overflow-hidden"
      >
        <div className="w-60px bg-white rounded-12px">
          {nodeItems.map((item) => {
            return (
              <div
                key={item.key}
                className="w-full h-60px flex flex-col items-center justify-center cursor-pointer hover:bg-gray-100"
                onMouseDown={(e) => onStartDrag(e, item)}
              >
                <img src={item.icon} className="w-36px" />
                <div className="text-12px text-gray-500">{item.text}</div>
              </div>
            );
          })}
        </div>
      </div>
    )
  );
}
