<script>
  import { getAuthInfo, makeAuthHeaderForAxios } from "$lib/auth/Auth.js";
  import { makePost } from "$lib/tools/requests/requests.js";
  import { isStringEmptyOrSpaces } from "$lib/tools/strings/Strings";
  import { sayError, sayInfo } from "$lib/tools/toaster/Toaster.js";
  import { redirect } from "$lib/tools/url/URLTools.js";
  import { jwtDecode } from "jwt-decode";

  export let data;
  let { userData } = data;
  let { token } = data;
  let value_role = "1";

  let changingUser = false;
  let canChangeUser = true;

  $: checkFields(
    userData.name,
    userData.surname,
    userData.balance,
    value_role,
    userData.bid,
    userData.payout_bid
  );

  function checkFields(name, surname, balance, role, bid, payout_bid) {
    // balance = Number(balance);
    // bid = Number(balance);
    console.log(name, surname, balance, role, bid, payout_bid);
    
    if (isStringEmptyOrSpaces(name) || name.length < 2) {
      canChangeUser = false;
      return;
    }
    if ((bid !== 0 && !bid) || bid < 0) {
      canChangeUser = false;
      return;
    }
    if ((payout_bid !== 0 && !payout_bid) || payout_bid < 0) {
      canChangeUser = false;
      return;
    }
    if (isStringEmptyOrSpaces(surname) || surname.length < 2) {
      canChangeUser = false;
      return;
    }
    if (role === "-1") {
      canChangeUser = false;
      return;
    }
    if ((balance !== 0 && !balance) || balance < 0) {
      canChangeUser = false;
      return;
    }
    canChangeUser = true;
  }

  async function changeUserInfo() {
    changingUser = true;
    const userResult = await makePost(
      "admin/changeUser",
      {
        token: token,
        name: userData.name,
        surname: userData.surname,
        balance: userData.balance.toString(),
        rate: "0",
        can_trade: userData["can_trade"] ? "true":"false",
        can_trade_global: userData["can_trade_global"] ? "true":"false",
        role: value_role,
        bid: userData.bid.toString(),
        payout_bid: userData.payout_bid.toString()
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (userResult.status === 401) {
      sayError("Данные авторизации устарели");
      // window.location.href = "/";
      changingUser = false;
      redirect("/admin/");
      return;
    }
    if (userResult.error) {
      sayError("Не удалось изменить пользователя");
      changingUser = false;
      return;
    }
    sayInfo("Пользователь изменён!");
    document.getElementById("ref")?.click();
  }
</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="w-full flex flex-col gap-4 p-4 rounded-box bg-base-300">
      <label class={"input input-bordered flex items-center gap-2 "}>
        Имя:
        <input
          bind:value={userData.name}
          type="text"
          class="grow text-lg text-info"
        />
      </label>
      <label class={"input input-bordered flex items-center gap-2 "}>
        Фамилия:
        <input
          bind:value={userData.surname}
          type="text"
          class="grow text-lg text-info"
        />
      </label>
      <label class={"input input-bordered flex items-center gap-2 "}>
        Баланс (USDT):
        <input
          bind:value={userData.balance}
          type="number"
          min="0"
          class="grow text-lg text-info"
        />
      </label>
      <label class={"input input-bordered flex items-center gap-2 "}>
        Ставка (%):
        <input
          bind:value={userData.bid}
          type="number"
          min="0"
          class="grow text-lg text-info"
        />
      </label>
      <label class={"input input-bordered flex items-center gap-2 "}>
        Ставка на выплату (%):
        <input
          bind:value={userData.payout_bid}
          type="number"
          min="0"
          class="grow text-lg text-info"
        />
      </label>
      <select
        bind:value={value_role}
        class="select select-bordered w-full text-base"
      >
        <option disabled selected value="-1">Права доступа</option>
        <option value="1">Трейдер</option>
        <option value="2">Модератор</option>
        <option value="4">Администратор</option>
      </select>
      <div class="flex p-4 items-center gap-2">
        <p>Торговля:</p>
        <input
          bind:checked={userData["can_trade"]}
          type="checkbox"
          class="toggle toggle-primary"
        />
      </div>
      <button on:click={()=>{
        changeUserInfo();
      }} class="btn btn-primary text-base" disabled={changingUser || !canChangeUser}>
      Сохранить
      {#if changingUser}
      <span class="loading loading-spinner"></span>
      {/if}
      </button>
      <a href={window.location.pathname.replace("change", "profile")} class="hidden" id="ref"></a>
    </div>
  </div>
</div>
