<script>
  import { browser } from "$app/environment";
  import { checkAuthSync, getAuthInfo, makeAuthHeaderForAxios } from "$lib/auth/Auth";
  import { makeGet } from "$lib/tools/requests/requests";
  import { sayError } from "$lib/tools/toaster/Toaster";
  import { redirect } from "$lib/tools/url/URLTools";

  let users = [];
  let usersReady = false;

  async function getUsers() {
    if(checkAuthSync())
    {
        const result = await makeGet("getUsers", makeAuthHeaderForAxios(getAuthInfo()?.a));
        users = result.data;
        usersReady = true;
        // console.log(result);
    }
    else
    {
      sayError("Данные авторизации устарели");
      // window.location.href = "/";
      redirect("/admin/");
      return;
    }
  }

  if(browser)
  {
    getUsers();
  }
</script>

<div class="w-full flex flex-col gap-8">
  <div class="flex gap-4">
    <div class="bg-accent rounded-[4px] w-[10px] h-full"></div>
    <h1 class="text-2xl font-semibold">Все пользователи</h1>
  </div>
  <div class="w-full flex flex-col p-4 rounded-box bg-base-300">
    <div class="overflow-x-auto">
      {#if usersReady}
        <table class="table">
          <!-- head -->
          <thead>
            <tr>
              <th>Токен</th>
              <th>Имя</th>
              <th>Баланс</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <!-- row 1 -->
             {#each users as user}
             <tr class="hover:bg-neutral group">
                <th class="font-normal">{user["token"]}</th>
                <td class="font-semibold">{user["name"]} {user["surname"]}</td>
                <td>{(Number(user["balance"]))} {user["code"]}</td>
                <td>
                  <a href={"/admin/user/profile/"+user["token"]} class="btn btn-outline btn-info group-hover:btn-warning">Профиль</a>
                </td>
              </tr>
             {/each}
          </tbody>
        </table>
        {:else}
        <div class="flex p-4 w-full justify-center items-center">
          <span class="loading loading-spinner"></span>
        </div>
        {/if}
      </div>
  </div>
</div>
