<template>
  <div class="flex items-center justify-center h-screen bg-gray-100">
    <div class="w-full max-w-sm p-6 bg-white rounded-lg shadow-md">
      <h2 class="text-2xl font-bold text-center mb-6">Вход</h2>
      {{ tg_id }}
      <form @submit.prevent="login">
        <div class="mb-4">
          <label class="block text-gray-700 text-sm font-bold mb-2" for="username">Логин</label>
          <input
              v-model="username"
              type="text"
              id="username"
              class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          />
        </div>
        <div class="mb-6">
          <label class="block text-gray-700 text-sm font-bold mb-2" for="password">Пароль</label>
          <input
              v-model="password"
              type="password"
              id="password"
              class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline"
          />
        </div>
        <div class="flex items-center justify-between">
          <button
              type="submit"
              class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
          >
            Войти
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import qs from 'qs';
import { computed, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import apiClient from '@/services/axiosSetup';

const username = ref('');
const password = ref('');
const router = useRouter();
const route = useRoute();

// Получение tg_id
const tg_id = computed(() => {
  if (window.Telegram?.WebApp) {
    const tg = window.Telegram.WebApp;
    tg.expand();  // Разворачиваем приложение на весь экран
    return tg.initDataUnsafe.user?.id ?? null;  // Если tg_id нет, возвращаем null
  }
  return null;
});

// Функция для автоматического входа по tg_id
const autoLoginWithTgId = async () => {
  if (tg_id.value) {
    try {
      const response = await apiClient.post('/auth/token/tg?tg_id=' + tg_id.value );
      const token = response.data.access_token;
      localStorage.setItem('token', token);
      apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      await router.push(route.query['back'] ? route.query['back'].toString() : '/');
    } catch (error) {
      console.error(error);
      alert('Ошибка входа. Проверьте логин и пароль.');
    }
  }
};

// Вызов autoLoginWithTgId при загрузке компонента
onMounted(() => {
  autoLoginWithTgId();
});

// Основная функция для логина
const login = async () => {
  try {
    let response;
    if (tg_id.value) {
      response = await apiClient.post('/auth/token/tg', qs.stringify({ tg_id: tg_id.value }));
    } else {
      response = await apiClient.post('/auth/token', qs.stringify({
        username: username.value,
        password: password.value,
      }));
    }

    const token = response.data.access_token;
    localStorage.setItem('token', token);
    apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    await router.push(route.query['back'] ? route.query['back'].toString() : '/');
  } catch (error) {
    console.error(error);
    alert('Ошибка входа. Проверьте логин и пароль.');
  }
};
</script>

<style scoped>
body {
  background-color: #f0f2f5;
}
</style>
