import { useEffect, useMemo, useRef, useState } from "react";
import { Button, message, Tooltip } from "antd";
import { Graph } from "@antv/x6";
import { handleParseFowlAIData, replaceFlowId } from "@/utils";
import { getFlowNodeMetaByAi } from "@/utils/flow";
import { getDefaultDataByTheme } from "@/config/data";
import { PlusOutlined } from "@ant-design/icons";

import { defaultProject, topicData } from "@/config/data";
import { getTopicsByAiData, renderMindMap, buildTopic } from "@/pages/mindmap/render";
import { cloneDeep, throttle } from "lodash-es";
import { TopicType } from "@/enum";
import { traverseNode } from "@/pages/mindmap/mindmapHander";

export default function RenderGraph(props: {
  language: string;
  json: string;
  type?: "flow" | "mindmap";
  onInsert?: (data: any) => void;
  showInsert?: boolean;
}) {
  const { language, json, onInsert, showInsert = true, type = "flow" } = props;
  const containerRef = useRef<HTMLDivElement>(null);
  const graphRef = useRef<Graph>();
  const [messageApi, contextHolder] = message.useMessage();
  const parseData = useRef();
  const [graphType, setGraphType] = useState<"flowchart" | "mindmap">(
    "flowchart"
  );

  useEffect(() => {
    graphRef.current = new Graph({
      container: containerRef.current!,
      width: containerRef.current!.clientWidth,
      height: containerRef.current!.clientHeight,
      autoResize: true,
      panning: true,
      mousewheel: { enabled: true },
      interacting: {
        edgeLabelMovable: false,
        edgeMovable: false,
        nodeMovable: false,
        arrowheadMovable: false,
      },
      background: {
        color: "#f5f5f5",
      },
    });
  }, []);

  const loadMindmap = () => {
    const mindProjectInfo = cloneDeep(defaultProject);
    const mainTopic = buildTopic(TopicType.main, {
      label: "中心主题",
      fill: {
        ...topicData.fill,
        color1: "#30304D",
      },
      text: {
        ...topicData.text,
        fontSize: 30,
        color: "#fff",
      },
    });

    const result = getTopicsByAiData(
      JSON.parse(json),
      mainTopic.id,
      TopicType.branch,
      mainTopic
    );

    const render = () => {
      renderMindMap({
        topics: result.topics,
        pageSetting: mindProjectInfo.pageSetting,
        structure: mindProjectInfo.structure,
        theme: mindProjectInfo.theme,
        graph: graphRef.current!,
        showTool: false,
      });
      setTimeout(() => {
        graphRef.current?.zoomToFit({
          padding: 30,
        });
      }, 300);
    };

    render();

    graphRef.current?.on("node:change:data", (args) => {
      const { current, previous, cell } = args;
      if (
        current.width !== previous.width ||
        current.collapsed !== previous.collapsed
      ) {
        result.topics = traverseNode(result.topics, (topic) => {
          if (topic.id === cell.id) {
            topic.width = current.width;
            topic.collapsed = current.collapsed;
          }
          return topic;
        });
        throttle(render, 1000)();
      }
    });
  };

  useEffect(() => {
    if (json.includes("shape")) {
      handleParseFowlAIData({
        content: json,
        message: {
          key: "ai-creator",
          instance: messageApi,
        },
        onSuccess: (data) => {
          console.log('data: ', data)
          const result = replaceFlowId(data);
          parseData.current = result;
          // graphRef.current?.fromJSON(data);
          const defaultDataByTheme = getDefaultDataByTheme("1");

          const list = (Array.isArray(result) ? result : [result]).map((item) =>
            getFlowNodeMetaByAi(item, defaultDataByTheme)
          );

          list.forEach((cell) => {
            if (cell.shape !== "edge") {
              graphRef.current?.addNode(cell);
            }
            if (cell.shape === "edge") {
              graphRef.current?.addEdge(cell);
            }
          });
          graphRef.current?.zoomToFit({
            padding: 20,
          });
        },
        onError: (err) => {
          messageApi.error(err.message);
        },
      });
    } else {
      setGraphType("mindmap");
      loadMindmap();
    }
  }, [language, json]);

  const addButton = useMemo(() => {
    if (showInsert && type === "flow" && graphType === "flowchart") {
      return (
        <Tooltip title="添加到当前画布">
          <Button
            variant="text"
            size="small"
            color="primary"
            icon={<PlusOutlined />}
            onClick={() => onInsert?.(parseData.current)}
          >
            加入画布
          </Button>
        </Tooltip>
      );
    }
    if (showInsert && type === "mindmap" && graphType === "mindmap") {
      return (
        <Tooltip title="添加到选择的主题">
          <Button
            variant="text"
            size="small"
            color="primary"
            icon={<PlusOutlined />}
            onClick={() => onInsert?.(JSON.parse(json))}
          >
            加入画布
          </Button>
        </Tooltip>
      );
    }
    return <></>;
  }, [graphType, showInsert]);

  return (
    <div className="w-full">
      {contextHolder}
      <div className="text-14px">为您生成以下内容:</div>
      <div
        className="w-full h-300px max-h-300px rounded-4px"
        ref={containerRef}
      />
      <div className="flex mt-8px">
        {addButton}
      </div>
    </div>
  );
}
