<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { apiGetTeam } from './client';
import { UnauthorizedError } from './UnauthorizedError';

const router = useRouter();

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

async function onClickLogin() {
  const oldText = buttonText.value
  buttonText.value = "Загрузка..."
  errorMsg.value = ""

  try {
    await apiGetTeam(login.value, password.value)
  } catch (error: unknown) {
    if (error instanceof UnauthorizedError) {
      // Действия при 401:
      // Вывести ошибку
      if (login.value == "" && password.value == "") {
        return
      }
      errorMsg.value = "Не верны название команды или пароль"
    } else {
      errorMsg.value = "Сервер не доступен"
    }
    return
  } finally {
    buttonText.value = oldText
  }

  sessionStorage.setItem("teamId", login.value)
  sessionStorage.setItem("password", password.value)
  router.push('/');
}

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>
.input-custom {
  width: 100%;
  box-sizing: border-box; /* обязательно! */
  margin-right: 15px;
}

.error-message {
  color: brown;
  margin: 16px 0;
}

.input-custom, .button-custom {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 15px;
  font-size: 16px;
}

.button-container {
  display: flex;
}
</style>
