<script>
  import { isStringEmptyOrSpaces } from "$lib/tools/strings/Strings";
  import { makePost, makeGet } from "$lib/tools/requests/requests";
  import {
    checkAuthSync,
    getAuthInfo,
    makeAuthHeaderForAxios,
  } from "$lib/auth/Auth";
  import { onMount } from "svelte";
  import { sayError } from "$lib/tools/toaster/Toaster";
  import { redirect } from "$lib/tools/url/URLTools";
  import { error } from "@sveltejs/kit";
  import { browser } from "$app/environment";

  let value_name = "";
  let value_surname = "";
  let value_balance = 0;
  let value_role = "-1";
  let value_bid = 0;
  let value_trading = false;
  let value_withdraw = false;
  let value_currency_code = "-1";
  let value_paid_bid = 0;
  let value_deposit_address = "";

  $: checkFields(
    value_name,
    value_surname,
    value_balance,
    value_role,
    value_bid,
    value_currency_code,
    value_paid_bid,
    value_deposit_address,
    value_insurance
  );

  function checkFields(
    name,
    surname,
    balance,
    role,
    bid,
    code,
    pbid,
    addr,
    insurance
  ) {
    if (isStringEmptyOrSpaces(code) || code === "-1") {
      canCreateUser = false;
      return;
    }
    if (!Number.isFinite(insurance) || insurance < 0) {
      canCreateUser = false;
      return;
    }
    if (isStringEmptyOrSpaces(addr) || addr.length < 8) {
      canCreateUser = false;
      return;
    }
    if (isStringEmptyOrSpaces(name) || name.length < 3) {
      canCreateUser = false;
      return;
    }
    if ((bid !== 0 && !bid) || bid < 0) {
      canCreateUser = false;
      return;
    }
    if (isStringEmptyOrSpaces(surname) || surname.length < 3) {
      canCreateUser = false;
      return;
    }
    if (role === "-1" || isStringEmptyOrSpaces(role)) {
      canCreateUser = false;
      return;
    }
    if ((balance !== 0 && !balance) || balance < 0) {
      canCreateUser = false;
      return;
    }
    if ((pbid !== 0 && !pbid) || pbid < 0) {
      canCreateUser = false;
      return;
    }
    canCreateUser = true;
  }

  let canCreateUser = false;
  let loadingUserToken = false;
  let userToken = "";

  let temp_userToken = "";

  async function createUser() {
    loadingUserToken = true;
    const result = await makePost(
      "createUser",
      {
        code: value_currency_code,
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (result.status === 401) {
      sayError("Данные авторизации устарели");
      redirect("/admin/");
      return;
    }
    if (result.error) {
      sayError("Не удалось создать пользователя");
      return;
    }
    temp_userToken = result.data.token;
    setupNewUser();
  }

  let value_insurance = 0;
  async function setupNewUser() {
    //todo
    const result = await makePost(
      "admin/changeUser",
      {
        token: temp_userToken,
        name: value_name,
        surname: value_surname,
        balance: value_balance.toString(),
        rate: "0",
        can_trade: value_trading ? "true" : "false",
        can_trade_global: value_trading ? "true" : "false",
        role: value_role,
        payout_bid: Number(value_paid_bid) + "",
        bid: value_bid.toString(),
        deposit_address: value_deposit_address + "",
        insurance: value_insurance.toString(),
        is_withdrawal_available: value_withdraw ? "true" : "false",
      },
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (result.status === 401) {
      sayError("Данные авторизации устарели");
      // window.location.href = "/";
      redirect("/admin/");
      return;
    }
    if (result.error) {
      sayError("Не удалось настроить пользователя");
      return;
    }
    userToken = temp_userToken;
    loadingUserToken = false;
  }

  let currentCurrencies = [{ code: "" }];
  async function getCurrentCurrencies() {
    // Made on 4th of October. Happy Birthday Dear Alex!
    const result = await makeGet(
      "client/currencies/enabled",
      makeAuthHeaderForAxios(getAuthInfo()?.a)
    );
    if (result.error) {
      console.error("Error with currencies");
      sayError("Не удалось получить валюты");
      return;
    }
    currentCurrencies = result.data.data;
    if (!Array.isArray(currentCurrencies)) {
      currentCurrencies = [];
    }
  }

  if (browser) {
    getCurrentCurrencies();
  }
</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 gap-4 p-4 rounded-box bg-base-300">
    <label class={"input input-bordered flex items-center gap-2 "}>
      Имя:
      <input
        bind:value={value_name}
        type="text"
        class="grow text-lg text-info"
      />
    </label>
    <label class={"input input-bordered flex items-center gap-2 "}>
      Фамилия:
      <input
        bind:value={value_surname}
        type="text"
        class="grow text-lg text-info"
      />
    </label>
    <label class={"input input-bordered flex items-center gap-2 "}>
      Баланс (USDT):
      <input
        bind:value={value_balance}
        type="number"
        min="0"
        class="grow text-lg text-info"
      />
    </label>
    <label class={"input input-bordered flex items-center gap-2 "}>
      Страховка (USDT):
      <input
        bind:value={value_insurance}
        type="number"
        min="0"
        class="grow text-lg text-info"
      />
    </label>
    <label class={"input input-bordered flex items-center gap-2 "}>
      Ставка (%):
      <input
        bind:value={value_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={value_paid_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={value_deposit_address}
        type="text"
        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>
      <option value="5">Тим лид</option>
    </select>
    <select
      bind:value={value_currency_code}
      class="select select-bordered w-full text-base"
    >
      <option disabled selected value="-1">Валюта</option>
      {#each currentCurrencies as currency}
        <option value={currency.code}>{currency.code}</option>
      {/each}
      <!-- <option value="KGS">KGS</option> -->
      <!-- <option value="2">Модератор</option>
      <option value="4">Администратор</option> -->
    </select>
    <div class="flex p-1 items-center gap-2">
      <p>Торговля:</p>
      <input
        bind:checked={value_trading}
        type="checkbox"
        class="toggle toggle-primary"
      />
    </div>
    <div class="flex p-1 items-center gap-2">
      <p>Доступ к выплатам:</p>
      <input
        bind:checked={value_withdraw}
        type="checkbox"
        class="toggle toggle-primary"
      />
    </div>
    <button
      on:click={() => {
        createUser();
      }}
      class={"btn text-base " +
        (loadingUserToken ? "btn-warning " : "btn-primary ") +
        (userToken !== "" ? "disabled:text-info" : "disabled:text-warning") +
        (canCreateUser ? "" : "disabled:text-opacity-50")}
      disabled={!canCreateUser || loadingUserToken || userToken !== ""}
    >
      {#if loadingUserToken}
        {"Ожидайте токен"}
        <span class="loading loading-spinner"></span>
      {:else if userToken === ""}
        {"Создать пользователя"}
      {:else if canCreateUser}
        {"Пользователь создан"}
      {/if}
    </button>
    {#if userToken !== ""}
      <div class="w-full flex p-4">
        <p class="text-xl">
          Токен пользователя: <span class="text-info text-xl">{userToken}</span>
        </p>
      </div>
    {/if}
  </div>
</div>
