<template>
  <div class="flex items-center justify-center min-h-screen bg-gray-100">
    <Card class="w-full max-w-md p-6 bg-white rounded-2xl shadow-lg">
      <template #title>
        <h2 class="text-2xl font-bold text-center text-gray-800">Регистрация</h2>
      </template>
    <Toast/>
      <template #content>
        <form @submit.prevent="submitHandler">
          <div class="mb-4">
            <label for="username" class="block mb-1 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-4">
            <label for="firstName" class="block mb-1 text-sm font-semibold text-gray-700">Имя</label>
            <InputText id="firstName" v-model.trim="firstName" class="w-full" :class="{'p-invalid': errors.firstName}" />
            <small v-if="errors.firstName" class="text-red-500">{{ errors.firstName }}</small>
          </div>

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

          <div class="mb-4">
            <label for="confirmPassword" class="block mb-1 text-sm font-semibold text-gray-700">Подтвердите пароль</label>
            <Password id="confirmPassword" v-model="confirmPassword" class="w-full" :feedback="false" :class="{'p-invalid': errors.confirmPassword}" toggleMask />
            <small v-if="errors.confirmPassword" class="text-red-500">{{ errors.confirmPassword }}</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="/login" class="text-blue-500 hover:underline">Войти</RouterLink>
        </p>
      </template>
    </Card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { 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 Toast from "primevue/toast";
import {useUserStore} from "@/stores/userStore";

const router = useRouter()
const toast = useToast()
const userStore = useUserStore()

const username = ref('')
const firstName = ref('')
const password = ref('')
const confirmPassword = ref('')
const loading = ref(false)

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

const validateForm = () => {
  errors.value = { username: '', firstName: '', password: '', confirmPassword: '' }
  let valid = true

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

  if (!firstName.value) {
    errors.value.firstName = 'Введите имя'
    valid = false
  }

  if (!password.value || password.value.length < 3) {
    errors.value.password = 'Пароль должен содержать минимум 6 символов'
    valid = false
  }

  if (password.value !== confirmPassword.value) {
    errors.value.confirmPassword = 'Пароли не совпадают'
    valid = false
  }

  return valid
}

const submitHandler = async () => {
  if (!validateForm()) return

  loading.value = true
  try {
    // Симуляция запроса (замени на реальный API-запрос)
    await userStore.register(username.value, password.value, firstName.value)

    toast.add({ severity: 'success', summary: 'Успешная регистрация', detail: 'Теперь вы можете войти', life: 3000 })
    await router.push('/login')
  } catch (error) {
    errors.value.username = error.response.data.message
    toast.add({ severity: 'error', summary: 'Ошибка регистрации', detail: 'Попробуйте позже', life: 3000 })
  } finally {
    loading.value = false
  }
}
</script>

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