import { useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { api } from "./api";
import { qk } from "./queryKeys";
import { notify } from "./notifications";

/** The shared channel-tag mutation flow used by both the channel manager and the channel detail
 *  page: optimistic attach/detach + a create-then-attach shortcut, with the cache-shape-specific
 *  optimistic update injected (the manager maps over a ManagedChannel[]; the detail patches one
 *  ChannelDetail). Keeps the two call sites from drifting. */
export function useChannelTagActions(opts: {
  /** Apply the optimistic tag change to whichever cache the caller owns. `attach` true = add. */
  optimisticToggle: (channelId: string, tagId: number, attach: boolean) => void;
  /** Called after the attach/detach lands (e.g. sync a sibling cache). Optional. */
  onSuccess?: (channelId: string) => void;
  /** Called if the attach/detach fails — revert by refetching the owning cache. */
  onError: (channelId: string) => void;
}) {
  const qc = useQueryClient();
  const { t } = useTranslation();

  const toggleTag = (channelId: string, tagId: number, hasTag: boolean) => {
    opts.optimisticToggle(channelId, tagId, !hasTag);
    const call = hasTag
      ? api.detachChannelTag(channelId, tagId)
      : api.attachChannelTag(channelId, tagId);
    call.then(() => opts.onSuccess?.(channelId)).catch(() => opts.onError(channelId));
  };

  // Create a brand-new personal tag and attach it in one step (so tagging doesn't require the
  // top-of-page "Manage tags" dialog first). Refresh the tag catalog so it appears everywhere.
  const createAndAttachTag = (channelId: string, name: string) => {
    api
      .createTag({ name })
      .then((tag) => {
        qc.invalidateQueries({ queryKey: qk.tags() });
        toggleTag(channelId, tag.id, false);
      })
      .catch(() => notify({ level: "error", message: t("channels.tags.createFailed") }));
  };

  return { toggleTag, createAndAttachTag };
}
