import { appApi } from 'src/boot/axios';
import { ref, computed } from 'vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { i18n } from 'boot/lang';
import type { Users } from 'src/vueLib/models/users';

export function useUserTable() {
  const users = ref<Users>([]);

  const pagination = ref({
    sortBy: 'user',
    descending: false,
    page: 1,
    rowsPerPage: 10,
  });

  const columns = computed(() => [
    {
      name: 'id',
      align: 'left' as const,
      label: 'Id',
      field: 'id',
      sortable: true,
      style: 'width: 50px; max-width: 50px;',
    },
    {
      name: 'user',
      align: 'left' as const,
      label: i18n.global.t('user'),
      field: 'user',
      sortable: true,
    },
    {
      name: 'email',
      align: 'left' as const,
      label: i18n.global.t('email'),
      field: 'email',
      sortable: true,
    },
    {
      name: 'role',
      align: 'left' as const,
      label: i18n.global.t('role'),
      field: 'role',
      sortable: true,
      style: 'width: 120px; max-width: 120px;',
    },
    { name: 'option', align: 'center' as const, label: '', field: 'option', icon: 'option' },
  ]);

  const { NotifyResponse } = useNotify();

  const loading = ref(false);

  //updates user list from database
  function updateUsers() {
    loading.value = true;

    appApi
      .get('secure/users')
      .then((resp) => {
        if (resp.data === null) {
          users.value = [];
          return;
        }
        users.value = resp.data as Users;
        if (users.value === null) {
          users.value = [];
          return;
        }
      })

      .catch((err) => {
        NotifyResponse(err, 'error');
      })
      .finally(() => {
        loading.value = false;
      });
  }
  return {
    users,
    pagination,
    columns,
    loading,
    updateUsers,
  };
}
