import { useMemo } from "react";
import { invoke } from "@tauri-apps/api/core";
import { emit } from "@tauri-apps/api/event";
import { logs } from "../data/mockData";
import Terminal from "../components/Terminal";
import TitleBar from "../components/TitleBar";
import EngineWorkbench from "./EngineWorkbench";
import PlaceholderWindow from "./PlaceholderWindow";
import SettingsWindow from "./SettingsWindow";
import { closeWindow } from "../utils/navigation";

export default function SecondaryWindow({ route, theme, setTheme, settingSection, setSettingSection }) {
  const title = useMemo(() => {
    if (route.includes("settings")) return "设置";
    if (route.includes("engine-workbench")) return "微信引擎工作台";
    if (route.includes("engine-logs")) return "分身引擎日志";
    if (route.includes("knowledge-create")) return "新增知识库";
    if (route.includes("knowledge-detail")) return "知识库详情";
    if (route.includes("skill")) return "skill技能详情";
    if (route.includes("employee-detail")) return "员工蒸馏详情";
    if (route.includes("distill-start")) return "开始蒸馏";
    return "二级窗口";
  }, [route]);

  async function closeEngineWorkbench() {
    await invoke("stop_agent").catch(() => {});
    await invoke("stop_vision_stream").catch(() => {});
    await emit("engine-state-changed", { enabled: false });
    await closeWindow();
  }

  return (
    <div className="app-window flex h-dvh w-full flex-col overflow-hidden rounded-[12px]">
      <TitleBar
        title={title}
        theme={theme}
        setTheme={setTheme}
        compact
        onClose={route.includes("engine-workbench") ? closeEngineWorkbench : undefined}
      />
      <main className="content-canvas flex min-h-0 flex-1 flex-col overflow-hidden">
        {route.includes("settings") ? (
          <SettingsWindow active={settingSection} setActive={setSettingSection} />
        ) : route.includes("engine-workbench") ? (
          <EngineWorkbench />
        ) : route.includes("engine-logs") ? (
          <div className="flex h-full min-h-0 p-5"><Terminal title="完整运行日志" lines={[...logs, ...logs, ...logs]} tall /></div>
        ) : (
          <PlaceholderWindow title={title} route={route} />
        )}
      </main>
    </div>
  );
}
