import { watch, onMounted, onBeforeUnmount, type Ref } from "vue";
import { useVueFlow } from "@vue-flow/core";
import { getFlow, saveFlow, type FlowSnapshot } from "@/api/flow";

/**
 * 画布持久化：防抖自动保存、按 projectId 恢复、旧数据迁移
 */
export function useFlowPersistence(
  projectId: string,
  nodes: Ref<any[]>,
  edges: Ref<any[]>,
) {
  const { toObject, setViewport, viewport } = useVueFlow();

  let isRestoring = false;
  let saveTimer: ReturnType<typeof setTimeout> | null = null;
  const SAVE_DEBOUNCE = 800;

  // 把当前画布序列化为快照
  const buildSnapshot = (): FlowSnapshot => toObject() as unknown as FlowSnapshot;

  // 防抖保存：节点/连线/视口任何变化都触发，800ms 合并
  const scheduleSave = () => {
    if (isRestoring) return;
    if (saveTimer) clearTimeout(saveTimer);
    saveTimer = setTimeout(async () => {
      saveTimer = null;
      try {
        await saveFlow(projectId, buildSnapshot());
      } catch (err) {
        console.error("画布自动保存失败", err);
      }
    }, SAVE_DEBOUNCE);
  };

  // 立即保存（用于页面卸载前）
  const flushSave = async () => {
    if (saveTimer) {
      clearTimeout(saveTimer);
      saveTimer = null;
    }
    if (isRestoring) return;
    try {
      await saveFlow(projectId, buildSnapshot());
    } catch (err) {
      console.error("画布保存失败", err);
    }
  };

  // 旧数据迁移：把 node.data.content 迁移到 node.data.panel
  const migrateLegacyContent = () => {
    nodes.value.forEach((n: any) => {
      if (n.data?.panel) {
        n.data.panel = {
          content: n.data.panel.content ?? "",
          selectValue: n.data.panel.selectValue ?? "",
          imgUrl: n.data.panel.imgUrl ?? "",
          videoUrl: n.data.panel.videoUrl ?? "",
        };
        return;
      }
      n.data = {
        ...(n.data ?? {}),
        panel: {
          content: (n.data?.content as string) ?? "",
          selectValue: "",
          imgUrl: "",
          videoUrl: "",
        },
      };
      if ("content" in (n.data ?? {})) delete n.data.content;
    });
  };

  // 挂载时按 projectId 拉取画布并恢复
  const restoreFlow = async () => {
    try {
      const data = await getFlow(projectId);
      if (!data) return;
      isRestoring = true;
      if (Array.isArray(data.nodes)) nodes.value = data.nodes;
      if (Array.isArray(data.edges)) edges.value = data.edges;
      migrateLegacyContent();
      const vp = data.viewport;
      if (vp) {
        await setViewport(vp).catch(() => void 0);
      }
    } catch (err) {
      console.warn("加载画布失败（可能是新项目）", err);
    } finally {
      setTimeout(() => {
        isRestoring = false;
      }, 0);
    }
  };

  // 监听画布变化 → 自动保存
  watch([nodes, edges], scheduleSave, { deep: true });
  watch(viewport, scheduleSave, { deep: true });

  // 页面关闭/刷新前尽力保存一次
  const onBeforeUnload = () => {
    flushSave();
  };
  window.addEventListener("beforeunload", onBeforeUnload);
  onBeforeUnmount(() => {
    window.removeEventListener("beforeunload", onBeforeUnload);
    flushSave();
  });

  return { restoreFlow, flushSave, buildSnapshot };
}
