<script setup lang="ts">
import { ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { getApiErrorMessage } from '@/services/api'

const auth = useAuthStore()
const route = useRoute()
const email = ref('')
const password = ref('')
const error = ref('')
const loading = ref(false)

function safeRedirectPath() {
  const redirect = String(route.query.redirect || '/')

  return redirect.startsWith('/') && !redirect.startsWith('//') ? redirect : '/'
}

async function submit() {
  error.value = ''
  loading.value = true

  try {
    await auth.login({ email: email.value, password: password.value }, safeRedirectPath())
  } catch (loginError) {
    error.value = getApiErrorMessage(loginError, 'Email or password is incorrect.')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <section class="panel form-page">
    <h2>Login</h2>
    <p>Access your BizNovia workspace.</p>

    <form class="form" @submit.prevent="submit">
      <div class="field">
        <label for="email">Email</label>
        <input id="email" v-model="email" autocomplete="email" type="email" required />
      </div>

      <div class="field">
        <label for="password">Password</label>
        <input id="password" v-model="password" autocomplete="current-password" type="password" required />
      </div>

      <p v-if="error" class="error">{{ error }}</p>
      <button class="button primary" type="submit" :disabled="loading || !email || !password">
        {{ loading ? 'Signing in...' : 'Login' }}
      </button>

      <RouterLink class="muted-link" to="/forgot-password">Forgot password?</RouterLink>
    </form>
  </section>
</template>
