<script setup>
import { ref } from 'vue'
import { login as apiLogin } from '@/services/authService.js'

const props = defineProps({
  currentPage: String,
})

const emit = defineEmits(['update'])

const login = ref('')
const password = ref('')
const authError = ref(false)
const isLoading = ref(false)

async function handleLogin() {
  isLoading.value = true
  authError.value = false

  try {
    const data = await apiLogin(login.value, password.value)
    if (data.message === 'Login successful') {
      emit('update', 'rezylt')
    } else {
      authError.value = true
    }
  } catch (err) {
    authError.value = true
    console.error(err)
  } finally {
    isLoading.value = false
  }
}

function handleKeyDown(event) {
  if (event.key === 'Enter') {
    handleLogin()
  }
}

function showStartPage() {
  emit('update', 'admin-panel')
  login.value = ''
  password.value = ''
  authError.value = false
}
</script>

<template>
  <div
    v-if="currentPage === 'admin-panel'"
    class="p-6 bg-white rounded-xl shadow max-w-md mx-auto mt-10 dark:bg-gray-800 dark:text-neutral-300"
  >
    <h2 class="text-xl font-semibold mb-4">Вход для администратора</h2>
    <div class="mb-3">
      <label class="block mb-1 text-sm">Логин</label>
      <input
        v-model="login"
        type="text"
        class="border rounded-lg p-2 w-full dark:bg-gray-900 dark:border-gray-600"
        @keydown="handleKeyDown"
      />
    </div>
    <div class="mb-4">
      <label class="block mb-1 text-sm">Пароль</label>
      <input
        v-model="password"
        type="password"
        class="border rounded-lg p-2 w-full dark:bg-gray-900 dark:border-gray-600"
        @keydown="handleKeyDown"
      />
    </div>
    <button
      type="button"
      :disabled="isLoading"
      class="mr-2 bg-teal-600 hover:bg-teal-800 text-white px-4 py-2 rounded-lg cursor-pointer disabled:opacity-50"
      @click="handleLogin"
    >
      {{ isLoading ? 'Вход...' : 'Войти' }}
    </button>
    <button
      type="button"
      class="dark:bg-gray-600 dark:hover:bg-gray-700 bg-gray-500 hover:bg-gray-600 px-4 py-2 rounded-lg cursor-pointer"
      @click="showStartPage"
    >
      Отмена
    </button>
    <div v-if="authError" class="mt-3 text-red-600 text-sm">
      Неверный логин или пароль
    </div>
  </div>
</template>

