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

const email = ref('')
const message = ref('')
const error = ref('')
const loading = ref(false)

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

  try {
    message.value = await authService.forgotPassword({
      email: email.value,
    })
  } catch (forgotPasswordError) {
    error.value = getApiErrorMessage(forgotPasswordError, 'Unable to send password reset link.')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <section class="panel form-page">
    <h2>Reset Password</h2>
    <p>Enter your account email to receive a secure reset link.</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>

      <p v-if="message" class="success">{{ message }}</p>
      <p v-if="error" class="error">{{ error }}</p>

      <button class="button primary" type="submit" :disabled="loading || !email">
        {{ loading ? 'Sending...' : 'Send Reset Link' }}
      </button>

      <RouterLink class="muted-link" to="/login">Back to login</RouterLink>
    </form>
  </section>
</template>
