import { ref } from "vue";
import type { Ref } from "vue";
import { apiPost } from "@/api/client";
import { useToastStore } from "@/stores/toast";

export function useTagSuggestions(
  title: Ref<string>,
  body: Ref<string>,
  tags: Ref<string[]>,
  markDirty: () => void,
) {
  const suggestedTags = ref<string[]>([]);
  const appliedTags = ref<Set<string>>(new Set());
  const suggestingTags = ref(false);

  async function fetchTagSuggestions() {
    if (suggestingTags.value) return;
    suggestingTags.value = true;
    suggestedTags.value = [];
    appliedTags.value = new Set();
    const toast = useToastStore();
    try {
      const res = await apiPost<{ suggested_tags: string[] }>("/api/notes/suggest-tags", {
        title: title.value,
        body: body.value,
        current_tags: tags.value,
      });
      suggestedTags.value = res.suggested_tags;
    } catch {
      toast.show("Failed to get tag suggestions", "error");
    } finally {
      suggestingTags.value = false;
    }
  }

  function applyTagSuggestion(tag: string) {
    if (appliedTags.value.has(tag)) return;
    if (!tags.value.includes(tag)) {
      tags.value = [...tags.value, tag];
    }
    appliedTags.value.add(tag);
    markDirty();
  }

  function dismissTagSuggestions() {
    suggestedTags.value = [];
    appliedTags.value = new Set();
  }

  return {
    suggestedTags,
    appliedTags,
    suggestingTags,
    fetchTagSuggestions,
    applyTagSuggestion,
    dismissTagSuggestions,
  };
}
