<template>
  <div class="flex flex-col items-center justify-center h-screen bg-gray-100">
    <Card class="w-full max-w-sm p-6 bg-white rounded-lg shadow-md">
      <template #title>
        <h2 class="text-2xl font-bold text-center">Вход</h2>
      </template>

      <template #content>
        <div v-if="tg_id" class="mb-4 text-center text-gray-600">
          Авторизация через Telegram (ID: {{ tg_id }})
        </div>

        <form @submit.prevent="login">
          <div class="mb-4">
            <label for="username" class="block text-sm font-semibold text-gray-700">Логин</label>
            <InputText id="username" v-model.trim="username" class="w-full" :class="{'p-invalid': errors.username}" />
            <small v-if="errors.username" class="text-red-500">{{ errors.username }}</small>
          </div>

          <div class="mb-6">
            <label for="password" class="block text-sm font-semibold text-gray-700">Пароль</label>
            <Password id="password" v-model="password" class="w-full" :feedback="false" toggleMask />
            <small v-if="errors.password" class="text-red-500">{{ errors.password }}</small>
          </div>

          <Button label="Войти" type="submit" class="w-full mt-2" :disabled="loading" :loading="loading" />
        </form>
      </template>

      <template #footer>
        <p class="mt-4 text-sm text-center text-gray-600">
          Нет аккаунта? <RouterLink to="/register" class="text-blue-500 hover:underline">Регистрация</RouterLink>
        </p>
      </template>
    </Card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from 'primevue/usetoast'
import InputText from 'primevue/inputtext'
import Password from 'primevue/password'
import Button from 'primevue/button'
import Card from 'primevue/card'
import { useUserStore } from '@/stores/userStore'
import apiClient from '@/services/axiosSetup'

const username = ref('')
const password = ref('')
const loading = ref(false)
const router = useRouter()
const route = useRoute()
const toast = useToast()
const userStore = useUserStore()

const errors = ref({ username: '', password: '' })

// Получение tg_id (Telegram ID)
const tg_id = computed(() => {
  if (window.Telegram?.WebApp) {
    const tg = window.Telegram.WebApp
    tg.expand() // Разворачиваем WebApp
    return tg.initDataUnsafe.user?.id ?? null
  }
  return null
})

// Авто-вход по Telegram 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}`

      toast.add({ severity: 'success', summary: 'Вход выполнен', detail: 'Добро пожаловать!', life: 3000 })
      await router.replace(route.query['back'] ? route.query['back'].toString() : '/')
    } catch (error) {
      console.error(error)
      toast.add({ severity: 'error', summary: 'Ошибка входа', detail: 'Ошибка Telegram авторизации', life: 3000 })
    }
  }
}

// Проверка формы перед отправкой
const validateForm = () => {
  errors.value = { username: '', password: '' }
  let valid = true

  if (!username.value) {
    errors.value.username = 'Введите логин'
    valid = false
  }
  if (!password.value) {
    errors.value.password = 'Введите пароль'
    valid = false
  }
  return valid
}

// Основная функция входа
const login = async () => {
  if (!validateForm()) return

  loading.value = true
  try {
    await userStore.login(username.value, password.value)
    toast.add({ severity: 'success', summary: 'Успешный вход', detail: 'Добро пожаловать!', life: 3000 })
    // await router.push('/')
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Ошибка входа', detail: 'Неверные данные', life: 3000 })
  } finally {
    loading.value = false
  }
}

// Запуск авто-входа при загрузке страницы
onMounted(() => {
  autoLoginWithTgId()
})
</script>

<style scoped>
.p-invalid {
  border-color: red !important;
}
</style>