<script setup lang="ts">
import { AuthenticationService } from '@/services/AuthenticationService'
import { inject, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const router = useRouter()
const username = ref('')
const password = ref('')
const errorLogin = ref(false)
const { t } = useI18n()

const authService = inject<AuthenticationService>('auth')

async function login() {
  try {
    await authService?.login(username.value, password.value)
    router.push({ name: 'home' })
  } catch (error) {
    errorLogin.value = true
  }
  // if (username.value === 'admin' && password.value === 'password') {
  // localStorage.setItem('token', 'true')
  // router.push({ name: 'home' })
  // } else {
  //   alert('Invalid username or password')
  // }
}

// // Listen for update available event
// listen('tauri://update-available', () => {
//   console.log('Update is available!')
//   // You can show a dialog or notify the user here
// })

// // Listen for update not available event
// listen('tauri://update-not-available', () => {
//   console.log('No update available.')
// })

// // Listen for update download progress
// listen('tauri://update-download-progress', (event) => {
//   console.log('Update download progress:', event.payload)
//   // You can update a progress bar here
// })

// // Listen for update download finished
// listen('tauri://update-download-finished', () => {
//   console.log('Update download finished.')
//   // You can notify the user to restart the app
// })
</script>

<template>
  <div class="login">
    <h1 class="title">{{ $t('login') }}</h1>
    <div class="message is-danger">
      <div class="message-body" v-if="errorLogin">
        {{ $t('invalid-username-or-password') }}
      </div>
    </div>
    <form class="form" @submit.prevent="login">
      <div class="field">
        <label class="label">{{ $t('username') }}</label>
        <div class="control">
          <input
            class="input"
            type="text"
            v-model="username"
            :placeholder="t('username-placeholder')"
          />
        </div>
      </div>
      <div class="field">
        <label class="label">{{ $t('password') }}</label>
        <div class="control">
          <input
            class="input"
            type="password"
            v-model="password"
            :placeholder="t('password-placeholder')"
          />
        </div>
      </div>

      <div class="field is-grouped">
        <div class="control">
          <button class="button is-primary" type="submit">{{ $t('login-button') }}</button>
        </div>
        <!-- <div class="control">
          <button class="button">Cancel</button>
        </div> -->
      </div>
    </form>
  </div>
</template>
