import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { modesApi } from "../api/modules/modes";
import { useAsyncRequest } from "../composables/useAsyncRequest";

export const useModesStore = defineStore("modes", () => {
  const modes = ref([]);
  const activeTags = ref([]);

  const listRequest = useAsyncRequest();
  const toggleRequest = useAsyncRequest();

  const isLoading = computed(() => listRequest.isLoading.value);
  const error = computed(() => listRequest.error.value);
  const isLoadingToggle = computed(() => toggleRequest.isLoading.value);

  const activeSet = computed(() => new Set(activeTags.value));

  const isActive = (tag) => activeSet.value.has(tag);

  async function loadModes() {
    return listRequest.execute(async (signal) => {
      const [listResult, activeResult] = await Promise.all([
        modesApi.list({ signal }),
        modesApi.active({ signal }),
      ]);

      if (!listResult.ok) {
        return listResult;
      }
      if (!activeResult.ok) {
        return activeResult;
      }

      modes.value = listResult.data?.data?.modes || [];
      activeTags.value = activeResult.data?.data?.active || [];

      return { ok: true };
    });
  }

  async function enableMode(tag) {
    return toggleRequest.execute(async () => {
      const result = await modesApi.enable(tag);
      if (result.ok) {
        if (!activeTags.value.includes(tag)) {
          activeTags.value.push(tag);
        }
        const mode = modes.value.find((m) => m.tag === tag);
        if (mode) {
          mode.is_active = true;
        }
      }
      return result;
    });
  }

  async function disableMode(tag) {
    return toggleRequest.execute(async () => {
      const result = await modesApi.disable(tag);
      if (result.ok) {
        activeTags.value = activeTags.value.filter((t) => t !== tag);
        const mode = modes.value.find((m) => m.tag === tag);
        if (mode) {
          mode.is_active = false;
        }
      }
      return result;
    });
  }

  async function toggleMode(tag) {
    if (isActive(tag)) {
      return disableMode(tag);
    }
    return enableMode(tag);
  }

  return {
    modes,
    activeTags,
    isLoading,
    error,
    isLoadingToggle,
    isActive,
    loadModes,
    enableMode,
    disableMode,
    toggleMode,
  };
});
