<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { encodeUTF8ToBase64, getApiUrl } from './utils';

  const router = useRouter();

  const login = ref("")
  const password = ref("")
  const buttonText = ref("Вход")
  const errorMsg = ref("")

  function onClickLogin() {
    const oldText = buttonText.value
    buttonText.value = "Загрузка..."
    errorMsg.value = ""
    fetch(
      getApiUrl("/team"),
      {
        method: "GET",
        headers: {
          "X-Id": encodeUTF8ToBase64(login.value),
          "X-Password": password.value
        },
      }
    )
    .then(response => {
      if (response.status == 200) {
        sessionStorage.setItem("teamId", login.value)
        sessionStorage.setItem("password", password.value)
        router.push('/');
        return
      }
      if (response.status == 401) {
        if (login.value == "" && password.value == "") {
          return
        }
        errorMsg.value = "Не верны название команды или пароль"
        return
      }
      errorMsg.value = "ХЗ что это " + response
    })
    .catch(() => {
      errorMsg.value = "Сервер не доступен"
    })
    .finally(() => {buttonText.value = oldText});
  }
  onMounted(() => {
    login.value = sessionStorage.getItem("teamId") || ""
    password.value = sessionStorage.getItem("password") || ""

    onClickLogin()
  })
</script>

<template>
  <div class="header-block">
    Вечерний детектив
  </div>

  <div class="center-message">
    <form @submit.prevent="onClickLogin">
      <div>
        <input class="input-custom" v-model="login" type="text" placeholder="Название команды">
      </div>
      <div>
        <input class="input-custom" v-model="password" type="text" placeholder="Пароль" autocapitalize="off">
      </div>
      <div class="button-container">
        <button class="button-custom" type="submit">{{ buttonText }}</button>
      </div>
      <div class="error-message">
        {{ errorMsg }}
      </div>
    </form>
  </div>
</template>

<style scoped>
.error-message {
  color: brown;
  margin: 16px 0;
}
</style>
