import React, { useEffect, useState, useRef } from "react";
import { register } from "@antv/x6-react-shape";
import { Graph, Node } from "@antv/x6";
import { Button, Dropdown, Input, InputRef } from "antd";
import { Transform } from "@antv/x6-plugin-transform";
import { NodeType } from "@/enum";
import { getDropDownItems } from "./utils";
const NoticeNode = ({ node, graph }: { node: Node; graph: Graph }) => {
  const { text } = node.getData();
  const boxRef = useRef<HTMLDivElement>(null);
  const tranform = useRef<Transform>();
  const [isSelected, setIsSelected] = useState(false);
  const [content, setContent] = useState(text);
  const textAreaRef = useRef<InputRef>(null);
  const [editing, setEditing] = useState(false);
  const params = new URL(document.location.href.replace('#', '')).searchParams;
  const mode = params.get("mode") ?? "edit";

  useEffect(() => {
    setContent(text);
  }, [text]);

  useEffect(() => {
    graph.on("node:selected", (args) => {
      if (args.node.id === node.id) {
        if (!tranform.current) {
          tranform.current = new Transform({
            resizing: { enabled: true },
          });
          graph.use(tranform.current);
        } else {
          tranform.current.enable();
        }
        graph.createTransformWidget(node);
      } else {
        graph.clearTransformWidgets();
        tranform.current?.disable();
      }
    });
  }, []);

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

  // 进入编辑
  const handleSetEdit = () => {
    setEditing(mode === "edit");
  };

  // 文本编辑失焦
  const handleBlur = () => {
    node.prop("update:remark", {
      ...node.getData(),
      text: content,
    });
    node.setData({ lock: false });
    graph.unlockScroller();
    graph.enablePanning();
    graph.clearTransformWidgets();
    setEditing(false);
  };

  return (
    <>
      <div
        className="w-full flex justify-end absolute top--34px left-0"
        style={{ display: isSelected && mode === "edit" ? "flex" : "none" }}
      >
        <Dropdown
          menu={{ items: getDropDownItems(node, graph) }}
          overlayStyle={{ width: 120 }}
        >
          <Button
            type="text"
            className="text-primary-dark"
            icon={<i className="iconfont icon-gengduo" />}
          />
        </Dropdown>
      </div>
      <div className="relative w-full h-full bg-#eff8ff" ref={boxRef}>
        <div className="absolute w-full h-full flex flex-col">
          <Input.TextArea
            ref={textAreaRef}
            placeholder="请输入注释内容"
            variant="borderless"
            className="w-full resize-none! flex-1 color-#666"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            onBlur={handleBlur}
            onFocus={() => {
              node.setData({ lock: true });
              graph.lockScroller();
              graph.togglePanning();
            }}
          />
        </div>
        <div
          className="absolute w-full h-full"
          style={{ pointerEvents: editing ? "none" : "auto" }}
          onDoubleClick={handleSetEdit}
        ></div>
      </div>
    </>
  );
};

register({
  shape: "notice-node",
  component: NoticeNode,
  width: 300,
  height: 300,
  zIndex: 0,
  effect: ["data"],
  data: {
    type: NodeType.TEXT,
    text: "",
  },
});
