import { ref } from "vue";
import { useCsrfToken } from "./useCsrfToken";
import { useBuilderPrefix } from "./useBuilderPrefix";

export function useWidgetManager(initialHiddenKeys: string[]) {
  const csrf = useCsrfToken();
  const prefix = useBuilderPrefix();

  const hiddenKeys = ref<string[]>([...initialHiddenKeys]);

  function visibleWidgets<T extends { key: string }>(widgets: T[]): T[] {
    return widgets.filter((w) => !hiddenKeys.value.includes(w.key));
  }

  function hideableWidgets<T extends { hideable: boolean }>(widgets: T[]): T[] {
    return widgets.filter((w) => w.hideable);
  }

  async function hideWidget(key: string): Promise<void> {
    if (hiddenKeys.value.includes(key)) return;
    hiddenKeys.value.push(key);
    await fetch(`/${prefix}/dashboard/widgets/${key}/hide`, {
      method: "POST",
      headers: { "X-CSRF-TOKEN": csrf, Accept: "application/json" },
    });
  }

  async function showWidget(key: string): Promise<void> {
    hiddenKeys.value = hiddenKeys.value.filter((k) => k !== key);
    await fetch(`/${prefix}/dashboard/widgets/${key}/show`, {
      method: "POST",
      headers: { "X-CSRF-TOKEN": csrf, Accept: "application/json" },
    });
  }

  async function toggleWidget(key: string): Promise<void> {
    if (hiddenKeys.value.includes(key)) {
      await showWidget(key);
    } else {
      await hideWidget(key);
    }
  }

  return {
    hiddenKeys,
    visibleWidgets,
    hideableWidgets,
    hideWidget,
    showWidget,
    toggleWidget,
  };
}
