import { useState, useEffect } from "react";
import { NodeType } from "@/enum";
import { nodes, aiNode } from "@/components/nodes";

import start from "@/assets/wf_icon_start.gif";
import end from "@/assets/wf_icon_end.gif";
import autohandle from "@/assets/wf_icon_autohandle.gif";
import and from "@/assets/wf_icon_and.gif";
import handle from "@/assets/wf_icon_handle.gif";
import judge from "@/assets/wf_icon_judge.gif";
import or from "@/assets/wf_icon_or.gif";
import { Graph, Node } from "@antv/x6";

const items = [
  { key: NodeType.START, icon: start, text: "开始" },
  { key: NodeType.PROCESS, icon: handle, text: "处理" },
  { key: NodeType.AUTO_PROCESS, icon: autohandle, text: "自动处理" },
  { key: NodeType.DECISION, icon: or, text: "判断" },
  { key: NodeType.AND, icon: and, text: "与" },
  { key: NodeType.LINK, icon: judge, text: "连接" },
  { key: NodeType.END, icon: end, text: "结束" },
];

export default function NodeMenu(props: {
  graph?: Graph;
  onChange?: (n?: Node) => void;
  position?: { x: number; y: number };
}) {
  const { graph } = props;
  // 添加节点
  const handleAddNode = (type: NodeType) => {
    const node = nodes.find((item) => item.type === type);
    const { width = 100, height = 100 } = graph?.getGraphArea() || {};
    const rect = graph?.getAllCellsBBox();
    const y = rect ? rect.y + rect.height - 80 : height / 2 - 100;

    const n = graph?.addNode({
      shape: node?.name,
      position: props?.position || {
        x: width / 2 - 150,
        y,
      },
      data: node?.data,
    });

    props?.onChange?.(n);
  };

  const handleAddAiNode = (item: any) => {
    const { width = 100, height = 100 } = graph?.getGraphArea() || {};
    const rect = graph?.getAllCellsBBox();
    const y = rect ? rect.y + rect.height - 80 : height / 2 - 100;

    const n = graph?.addNode({
      shape: item?.name,
      position: props?.position || {
        x: width / 2 - 150,
        y,
      },
      data: {
        name: item.data.name,
        icon: item.icon,
        color: item.color,
        style: item.style,
        port: item.port,
        type: item.data.type,
        hidePort: item.data.hidePort,
      },
    });

    props?.onChange?.(n);
  };

  return (
    <div className="w-280px flex flex-wrap gap-[8px 12px]">
      {items.map((item) => {
        return (
          <div
            className="w-[38%] border-box h-40px px-12px rounded-8px flex items-center cursor-pointer hover:bg-#eff0f8"
            key={item.key}
            onClick={(e) => {handleAddNode(item.key)}}
          >
            <img src={item.icon} className="w-24px" />
            <span>{item.text}</span>
          </div>
        );
      })}
    </div>
  );
}
