<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { ApiError } from '../lib/api'
import { useAuthStore } from '../stores/auth'

const auth = useAuthStore()

const cooldown = ref(0)
let timer: ReturnType<typeof setInterval> | undefined

function startCooldown(seconds: number) {
  cooldown.value = Math.max(0, Math.ceil(seconds))
  clearInterval(timer)
  timer = setInterval(() => {
    cooldown.value -= 1
    if (cooldown.value <= 0) clearInterval(timer)
  }, 1000)
}

onBeforeUnmount(() => clearInterval(timer))

// --- resend verification -------------------------------------------------
const resending = ref(false)
const resendMessage = ref('')
const resendError = ref('')

async function onResend() {
  resending.value = true
  resendMessage.value = ''
  resendError.value = ''
  try {
    const retryAfter = await auth.resendVerification()
    resendMessage.value = `Sent. Check ${auth.user?.email}.`
    startCooldown(retryAfter)
  } catch (e) {
    if (e instanceof ApiError) {
      resendError.value = e.message
      if (e.status === 429) startCooldown(e.retryAfter ?? 60)
    } else {
      resendError.value = 'Could not send the email.'
    }
  } finally {
    resending.value = false
  }
}

// --- change email ------------------------------------------------------
const newEmail = ref('')
const password = ref('')
const changing = ref(false)
const changeMessage = ref('')
const changeError = ref<ApiError | null>(null)

async function onChangeEmail() {
  changing.value = true
  changeMessage.value = ''
  changeError.value = null
  try {
    const { pending_email, retry_after } = await auth.requestEmailChange(newEmail.value, password.value)
    changeMessage.value = `Confirmation link sent to ${pending_email}. Your address changes once you open it.`
    newEmail.value = ''
    password.value = ''
    startCooldown(retry_after)
  } catch (e) {
    changeError.value = e instanceof ApiError ? e : new ApiError('Could not request the change.', 0)
    if (e instanceof ApiError && e.status === 429) startCooldown(e.retryAfter ?? 60)
  } finally {
    changing.value = false
  }
}

const resendLabel = computed(() => {
  if (resending.value) return 'Sending…'
  if (cooldown.value > 0) return `Resend in ${cooldown.value}s`
  return 'Resend verification email'
})
</script>

<template>
  <section class="card">
    <p><RouterLink to="/">&larr; Back to lists</RouterLink></p>
    <h1>Your profile</h1>

    <p><strong>Email:</strong> {{ auth.user?.email }}</p>
    <p>
      <strong>Status:</strong>
      <span v-if="auth.emailVerified">verified</span>
      <span v-else class="badge badge--warn">not verified</span>
    </p>

    <div v-if="auth.user?.pending_email" class="notice">
      A change to <strong>{{ auth.user.pending_email }}</strong> is pending. Open the
      link we sent to that address to complete it. The link expires 15 minutes
      after it was sent.
    </div>

    <section v-if="!auth.emailVerified">
      <h2>Verify your email</h2>
      <p class="muted">
        We sent a link to {{ auth.user?.email }}. It expires 15 minutes after
        it's sent. You can resend it once a minute.
      </p>
      <button type="button" :disabled="resending || cooldown > 0" @click="onResend">
        {{ resendLabel }}
      </button>
      <p v-if="resendMessage" class="muted">{{ resendMessage }}</p>
      <p v-if="resendError" class="form-error">{{ resendError }}</p>
    </section>

    <section>
      <h2>Change email address</h2>
      <form class="form" @submit.prevent="onChangeEmail">
        <label>
          <span>New email</span>
          <input v-model="newEmail" type="email" maxlength="255" required />
          <small v-if="changeError?.fieldError('email')" class="field-error">
            {{ changeError.fieldError('email') }}
          </small>
        </label>
        <label>
          <span>Current password</span>
          <input v-model="password" type="password" autocomplete="current-password" required />
          <small v-if="changeError?.fieldError('password')" class="field-error">
            {{ changeError.fieldError('password') }}
          </small>
        </label>

        <p v-if="changeError && Object.keys(changeError.details).length === 0" class="form-error">
          {{ changeError.message }}
        </p>
        <p v-if="changeMessage" class="muted">{{ changeMessage }}</p>

        <button type="submit" :disabled="changing || cooldown > 0">
          {{ changing ? 'Sending…' : cooldown > 0 ? `Wait ${cooldown}s` : 'Send confirmation link' }}
        </button>
      </form>
    </section>
  </section>
</template>
