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";

// 常量配置抽取
const INITIAL_DATA: MindElixirData = {
  nodeData: {
    id: "root",
    topic: "中心主题",
  },
};
const LOADING_DATA: MindElixirData = {
  nodeData: {
    id: "root",
    topic: "生成中....",
  },
};

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();
  let { msg } = query.state || {};
  const [data, setData] = useState<MindElixirData>(INITIAL_DATA);

  useEffect(() => {
    // 确保容器元素已挂载
    if (!containerRef.current) return;
    // 初始化配置项
    const options: Options = {
      el: containerRef.current,
      locale: "zh_CN",
      draggable: true,
      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",
            );
            const cleanedContent = response.replace(/^```json|```$/g, "");
            const parsedData: MindElixirData = JSON.parse(cleanedContent);
            // 增强校验逻辑
            if (
              !parsedData?.nodeData?.id ||
              !Array.isArray(parsedData.nodeData.children)
            ) {
              throw new Error("数据结构不完整");
            }
            setData(parsedData);
            navigate(Path.Mind, { replace: true, state: { msg: null } });
          } catch (error) {
            console.log(error);
            message.error("请求失败,请重试");
          } finally {
            setIsLoading(false); // 确保关闭加载状态
          }
        }
      }
    };
    fetchData();

    return () => {
      if (mindInstance.current) {
        mindInstance.current.destroy();
      }
    };
  }, []);

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

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

  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>
    </>
  );
}