"use client";

import { useCallback, useState } from "react";
import type { DocumentSearchResult } from "@/types/search";
import type { ReferenceInsertMode } from "@/store/search-palette";
import { useEditorBridgeStore } from "@/store/editor-bridge";
import { recordRecentPage } from "@/lib/search/record-recent";

interface ReferenceComposerOptions {
  workspaceId: string | null;
  sourcePageId: string | null;
}

interface ComposeParams {
  mode: ReferenceInsertMode;
  alias?: string;
}

export function useReferenceComposer({ workspaceId, sourcePageId }: ReferenceComposerOptions) {
  const bridge = useEditorBridgeStore((state) => state.bridge);
  const [pending, setPending] = useState(false);

  const insertReference = useCallback(
    async (target: DocumentSearchResult, params: ComposeParams) => {
      if (!workspaceId || !sourcePageId) {
        window.alert("当前页面或工作空间信息缺失，无法插入引用");
        return;
      }
      if (!bridge) {
        window.alert("编辑器尚未准备好，请稍后再试");
        return;
      }

      const aliasText = params.alias?.trim();
      const label = aliasText || target.title || "无标题";
      const mode = params.mode;
      const result =
        mode === "inline"
          ? bridge.insertInlineReference(target, label)
          : bridge.insertEmbedReference(target);
      setPending(true);

      try {
        const response = await fetch("/api/references/record", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            workspaceId,
            sourcePageId,
            targetPageId: target.id,
            sourceBlockId: result?.blockId ?? null,
            alias: label,
            displayMode: mode,
            isPreviewable: true,
          }),
        });
        if (!response.ok) {
          const message = (await response.json().catch(() => null))?.error ?? "引用记录失败";
          window.alert(message);
        } else {
          void recordRecentPage(workspaceId, target.id);
        }
      } catch (error) {
        console.error(error);
        window.alert("引用记录失败，请稍后再试");
      } finally {
        setPending(false);
      }
    },
    [bridge, sourcePageId, workspaceId],
  );

  return {
    insertReference,
    referencing: pending,
  };
}
