<script setup lang="ts">
import { ref, computed } from 'vue'
import { RouterLink } from 'vue-router'
import { forgotPassword } from '@/api/auth'
import { ApiError } from '@/api/client'

const email = ref('')
const submitting = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

const isValid = computed(() => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value))

async function handleSubmit() {
  if (!isValid.value || submitting.value) return

  submitting.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const response = await forgotPassword(email.value)
    successMessage.value = response.message
  } catch (err) {
    if (err instanceof ApiError) {
      errorMessage.value = err.message
    } else {
      errorMessage.value = 'Något gick fel. Försök igen senare.'
    }
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="page">
    <div class="page__card">
      <h1 class="page__title">Glömt lösenord?</h1>
      <p class="page__subtitle">
        Ange din e-postadress så skickar vi en länk för att återställa
        lösenordet.
      </p>

      <form
        v-if="!successMessage"
        class="page__form"
        @submit.prevent="handleSubmit"
      >
        <div class="field">
          <label for="email" class="field__label">E-postadress</label>
          <input
            id="email"
            v-model="email"
            type="email"
            name="email"
            autocomplete="email"
            class="field__input"
            placeholder="namn@exempel.se"
          />
        </div>

        <div v-if="errorMessage" class="message message--error">
          {{ errorMessage }}
        </div>

        <button
          type="submit"
          class="btn btn--primary btn--lg page__submit"
          :disabled="!isValid || submitting"
        >
          {{ submitting ? 'Skickar...' : 'Skicka återställningslänk' }}
        </button>
      </form>

      <div v-else class="message message--success">
        {{ successMessage }}
      </div>

      <p class="page__footer-link">
        <RouterLink to="/logga-in">Tillbaka till inloggning</RouterLink>
      </p>
    </div>
  </div>
</template>

<style scoped>
.page {
  max-width: 28rem;
  margin: var(--space-3xl) auto 0;
  padding: 0 var(--space-lg);
}

.page__card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-xl);
  padding: var(--space-xl);
  box-shadow: var(--shadow-card);
}

.page__title {
  margin: 0 0 var(--space-sm) 0;
  font-size: 1.5rem;
  color: var(--color-ink);
}

.page__subtitle {
  margin: 0 0 var(--space-xl) 0;
  font-size: 0.875rem;
  color: var(--color-muted);
}

.page__form {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.page__footer-link {
  margin-top: var(--space-lg);
  text-align: center;
  font-size: 0.875rem;
}

.page__submit {
  width: 100%;
}
</style>
