import api from '@/api';
import { defaultSort, defaultCursor } from '@/constants/defaults';
import { ITEMS_PER_PAGE } from '@/constants/static';
import { Cursor } from '@/types/cursor';
import { Group } from '@/types/group';
import { OrderBy } from '@/types/order-by';

//
// MARK: Pagination
//
const page: Ref<number> = ref(1);
const perPage: Ref<number> = ref(ITEMS_PER_PAGE[0]);
const orderBy: Ref<OrderBy> = ref(JSON.parse(defaultSort));

const setPage = (v: number) => (page.value = v);
const setPerPage = (v: number) => (perPage.value = v);
const setSort = (v: OrderBy[]) => {
  if (!v || !v.length) {
    orderBy.value = JSON.parse(defaultSort);
  } else {
    orderBy.value = v[0];
  }
};

//
// MARK: Fetch all groups
//
const all: Ref<Group[]> = ref([]);
const selected: Ref<number[]> = ref([]);
const cursor: Ref<Cursor> = ref(JSON.parse(defaultCursor));

const loading: Ref<boolean> = ref(false);
const error: Ref<string> = ref('');

const resetSelected = () => (selected.value = []);
const getAll = async (): Promise<void> => {
  if (loading.value) {
    return;
  }

  resetError();
  setLoading(true);

  const [res, e] = await api.groups.getAll(
    perPage.value,
    page.value,
    orderBy.value,
    search.value,
  );
  if (e && typeof e === 'string') {
    error.value = e;
  } else {
    all.value = res?.data?.data !== null ? res?.data?.data : [];
    cursor.value = res?.data?.cursor;
    resetError();
    resetSelected;
  }

  setLoading(false);
};
const resetError = () => (error.value = '');
const setLoading = (state: boolean) => (loading.value = state);

//
// MARK: Search
//
const search: Ref<string> = ref('');
const cooldown: Ref<number | undefined> = ref();

const resetCooldown = (): void => {
  if (cooldown.value) {
    clearTimeout(cooldown.value);
    cooldown.value = undefined;
  }
};
const searchWithCooldown = (t: number): void => {
  if (cooldown.value) {
    resetCooldown();
  }

  const to = setTimeout(() => getAll(), t);
  cooldown.value = to;
};

export {
  page,
  perPage,
  orderBy,
  setPerPage,
  setPage,
  setSort,
  all,
  selected,
  cursor,
  loading,
  error,
  resetSelected,
  getAll,
  resetError,
  setLoading,
  search,
  cooldown,
  resetCooldown,
  searchWithCooldown,
};
