<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import { ApiError } from '@/api/client'
import { useAuthStore } from '@/stores/authStore'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

const token = ref('')
const password = ref('')
const submitting = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

onMounted(() => {
  const value = route.query.token
  token.value = typeof value === 'string' ? value : ''
  if (!token.value) {
    errorMessage.value = 'Bekräftelselänken saknar en giltig kod.'
  }
})

async function handleSubmit() {
  if (!token.value || password.value.length === 0 || submitting.value) return

  submitting.value = true
  errorMessage.value = ''

  try {
    await auth.confirmUserEmailChange(token.value, password.value)
    successMessage.value = 'Din e-postadress har uppdaterats.'
    setTimeout(() => router.push('/'), 2000)
  } catch (err) {
    if (err instanceof ApiError && err.status === 401) {
      errorMessage.value = 'Lösenordet är felaktigt'
    } else if (err instanceof ApiError) {
      errorMessage.value = err.message
    } else {
      errorMessage.value =
        'Något gick fel. Begär en ny bekräftelselänk från inställningar.'
    }
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="page">
    <div class="page__card">
      <h1 class="page__title">Bekräfta e-postadress</h1>

      <p v-if="token && !successMessage" class="page__subtitle">
        Ange ditt lösenord för att slutföra bytet av e-postadress.
      </p>

      <form
        v-if="token && !successMessage"
        class="page__form"
        @submit.prevent="handleSubmit"
      >
        <div class="field">
          <label for="password" class="field__label">Lösenord</label>
          <input
            id="password"
            v-model="password"
            type="password"
            name="password"
            autocomplete="current-password"
            class="field__input"
          />
        </div>

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

        <button
          type="submit"
          class="btn btn--primary btn--lg page__submit"
          :disabled="password.length === 0 || submitting"
        >
          {{ submitting ? 'Bekräftar...' : 'Bekräfta ny e-postadress' }}
        </button>
      </form>

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

      <div v-else-if="errorMessage" class="message message--error">
        {{ errorMessage }}
        <p class="page__footer-link">
          <RouterLink to="/andra-epost">Gå till inställningar</RouterLink>
        </p>
      </div>

      <p v-if="token && !successMessage" class="page__footer-link">
        <RouterLink to="/">Tillbaka till startsidan</RouterLink>
      </p>
    </div>
  </div>
</template>

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

.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>
