import { useQueryClient } from '@tanstack/vue-query';
import { GamaProp } from '@win2win/shared';
import { useFetch } from '@win2win/shared-ui';
import { has, orderBy } from 'lodash';
import { Gama, LayoutGroup } from 'src/models';
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';

export function useGama() {
  const route = useRoute();
  const store = useStore();
  const idGama = computed(() => (has(route.params, 'ID_GAMA') ? Number(route.params.ID_GAMA) : null));
  const gama = computed(() => (idGama.value !== null ? store.getters['gamas/gama'](idGama.value) : null));
  const props = computed<(GamaProp & { own: boolean })[]>(() => orderBy(gama.value?.PROPS || [], 'own', 'asc'));
  const require = computed(() => gama.value?.REQUIERE || {});
  const tags = computed(() => (gama.value?.TAGS || '').split(',').filter((t: string) => !!t.trim()));
  const collections = computed(() => gama.value?.COLLECTIONS || []);
  const loading = ref(false);

  const queryKey = computed(() => ['layouts', { idGama: idGama.value }]);
  const path = computed(() => `layouts?idGama=${idGama.value}`);
  const { data: layoutGroups, fetching: fetchingLayouts, invalidate } = useFetch<LayoutGroup[]>(queryKey, path);

  const refetchLayouts = () => {
    store.dispatch('gamas/refretchLayouts');
    invalidate();
  };

  const queryClient = useQueryClient();
  const refetch = (queryKey: any[]) => {
    queryClient.invalidateQueries({ queryKey, exact: false, refetchType: 'all' });
  };

  const updateGama = async (data: Partial<Gama>) => {
    loading.value = true;
    return store.dispatch('gamas/updateGama', { ID_GAMA: idGama.value, ...data }).finally(() => (loading.value = false));
  };

  return { updateGama, gama, loading, idGama, props, require, tags, collections, layoutGroups, fetchingLayouts, refetchLayouts, refetch };
}
