import chatStyles from "@/app/components/chat.module.scss";
import homeStyles from "@/app/components/home.module.scss";

import { MindSiderBar } from "./mind-siderBar";
import MindElixir, { type Options, type MindElixirData } from "mind-elixir";
import { WindowContent } from "@/app/components/home";
import { useMobileScreen } from "@/app/utils";
import { IconButton } from "../button";
import Locale from "@/app/locales";
import { Path } from "@/app/constant";
import { useNavigate, useLocation } from "react-router-dom";
import clsx from "clsx";
import { getClientConfig } from "@/app/config/client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useAppConfig } from "@/app/store";

import ReturnIcon from "@/app/icons/return.svg";
import MinIcon from "@/app/icons/min.svg";
import MaxIcon from "@/app/icons/max.svg";
import SDIcon from "@/app/icons/sd.svg";
import { useChatStore, useMindMapStore } from "@/app/store";
import { message } from "antd";

export function MindPage() {
  const isMobileScreen = useMobileScreen();
  const navigate = useNavigate();
  const clientConfig = useMemo(() => getClientConfig(), []);
  const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  const config = useAppConfig();
  const scrollRef = useRef<HTMLDivElement>(null);
  const isMind = location.pathname === Path.Mind;
  const [isLoading, setIsLoading] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const mindInstance = useRef<InstanceType<typeof MindElixir> | null>(null);
  const chatStore = useChatStore();
  const { newMessages, content } = useMindMapStore.getState();
  const query = useLocation();
  const { msg } = query.state || {};
  const [data, setData] = useState<MindElixirData>({
    nodeData: {
      id: "root",
      topic: "中心主题",
    },
  });

  useEffect(() => {
    // 确保容器元素已挂载
    if (!containerRef.current) return;
    // 初始化配置项
    const options: Options = {
      el: containerRef.current,
      contextMenu: true,
      toolBar: true,
      nodeMenu: true,
    };
    // 创建实例
    mindInstance.current = new MindElixir(options);
    mindInstance.current.init(data);

    const fetchData = async () => {
      if (msg) {
        if (content) {
          setIsLoading(true);
          try {
            const response = await chatStore.getMindData(
              newMessages,
              "gpt-4o-mini",
            );
            console.log("原始响应:", response);
            let cleanedContent = response.startsWith("```json")
              ? response.substring(8)
              : response;
            if (cleanedContent.endsWith("```")) {
              cleanedContent = cleanedContent.substring(
                0,
                cleanedContent.length - 4,
              );
            }
            const parsedData: MindElixirData = JSON.parse(cleanedContent);
            console.log("解析后响应:", parsedData);
            // 增强校验逻辑
            if (
              !parsedData?.nodeData?.id ||
              !Array.isArray(parsedData.nodeData.children)
            ) {
              throw new Error("数据结构不完整");
            }
            setData(parsedData);
          } catch (error) {
            console.log(error);
            message.error("请求失败,请重试");
          } finally {
            setIsLoading(false); // 确保关闭加载状态
          }
        }
      }
    };
    fetchData();

    return () => {
      if (mindInstance.current) {
        mindInstance.current.destroy();
        // 移除事件监听器
        document.removeEventListener("mousemove", () => {});
        document.removeEventListener("mouseup", () => {});
      }
    };
  }, []);

  useEffect(() => {
    mindInstance.current?.refresh(data);
  }, [data]);

  useEffect(() => {
    if (isLoading) {
      mindInstance.current?.refresh({
        nodeData: {
          id: "root",
          topic: "生成中....",
        },
      });
    } else {
      mindInstance.current?.refresh({
        nodeData: {
          id: "root",
          topic: "中心主题",
        },
      });
    }
  }, [isLoading]);

  // const meNode=document.querySelector('me-nodes')
  // const draggableElement = meNode?.querySelector('me-root') as HTMLElement | null;
  // if (draggableElement) {
  //     let isDragging = false; // 是否正在拖拽
  //     let startX = 0; // 鼠标按下时的 X 坐标
  //     let startY = 0; // 鼠标按下时的 Y 坐标
  //     let initialLeft = 0; // 元素初始的左偏移量
  //     let initialTop = 0; // 元素初始的上偏移量
  //     // 鼠标按下事件
  //     draggableElement.addEventListener('mousedown', (e) => {
  //         isDragging = true;
  //         startX = e.clientX;
  //         startY = e.clientY;
  //         // 获取 me-root 元素当前的位置
  //         const draggableStyle = window.getComputedStyle(draggableElement);
  //         initialLeft = parseInt(draggableStyle.left) || 0;
  //         initialTop = parseInt(draggableStyle.top) || 0;
  //         // 确保元素可以移动
  //         draggableElement.style.position = 'absolute';
  //     });
  //     // 鼠标移动事件
  //     document.addEventListener('mousemove', (e) => {
  //         if (isDragging) {
  //             const currentX = e.clientX;
  //             const currentY = e.clientY;
  //             // 计算偏移量
  //             const diffX = currentX - startX;
  //             const diffY = currentY - startY;
  //             // 更新 me-root 元素位置
  //             draggableElement.style.left = `${initialLeft + diffX}px`;
  //             draggableElement.style.top = `${initialTop + diffY}px`;
  //             // 检查 meMain 是否存在,如果存在则更新其位置
  //             const meMain = meNode?.querySelector('me-main') as HTMLElement | null;
  //             if (meMain) {
  //                 // 获取 meMain 元素当前的位置
  //                 const meMainStyle = window.getComputedStyle(meMain);
  //                 const meMainInitialLeft = parseInt(meMainStyle.left) || 0;
  //                 const meMainInitialTop = parseInt(meMainStyle.top) || 0;
  //                 // 更新 meMain 元素位置
  //                 meMain.style.position = 'absolute';
  //                 meMain.style.left = `${meMainInitialLeft + diffX}px`;
  //                 meMain.style.top = `${meMainInitialTop + diffY}px`;
  //             }
  //         }
  //     });

  //     // 鼠标释放事件
  //     document.addEventListener('mouseup', () => {
  //         isDragging = false;
  //     });
  // } else {
  //     console.error('未找到 me-root 元素');
  // }

  return (
    <>
      <MindSiderBar
        className={clsx({ [homeStyles["sidebar-show"]]: isMind })}
        setData={setData}
        isLoading={isLoading}
        setIsLoading={setIsLoading}
      />
      <WindowContent>
        <div className={chatStyles.chat} key={"1"}>
          <div className="window-header" data-tauri-drag-region>
            {isMobileScreen && (
              <div className="window-actions">
                <div className={"window-action-button"}>
                  <IconButton
                    icon={<ReturnIcon />}
                    bordered
                    title={Locale.Chat.Actions.ChatList}
                    onClick={() => navigate(Path.BgRemoval)}
                  />
                </div>
              </div>
            )}
            <div
              className={clsx(
                "window-header-title",
                chatStyles["chat-body-title"],
              )}
            >
              <div className={`window-header-main-title`}>生成思维导图</div>
            </div>
            <div className={chatStyles["chat-message-actions"]}>
              <div className={chatStyles["chat-input-actions"]}>
                {/* <ChatAction
                                    text={Locale.Chat.Actions.ReWrite}
                                    icon={<ReloadIcon />}
                                    onClick={() => { }
                                    }
                                /> */}
              </div>
            </div>
            <div className="window-actions">
              {showMaxIcon && (
                <div className="window-action-button">
                  <IconButton
                    aria={Locale.Chat.Actions.FullScreen}
                    icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
                    bordered
                    onClick={() => {
                      config.update(
                        (config) => (config.tightBorder = !config.tightBorder),
                      );
                    }}
                  />
                </div>
              )}
              {isMobileScreen && <SDIcon width={50} height={50} />}
            </div>
          </div>
          <div className={chatStyles["chat-body"]} ref={scrollRef}>
            <div ref={containerRef} style={{ width: "100%", height: "100%" }} />
          </div>
        </div>
      </WindowContent>
    </>
  );
}