<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { ApiError, apiRequest } from '../lib/api'
import { passkeysSupported, registerPasskey } from '../lib/webauthn'
import { useAuthStore } from '../stores/auth'
import type { Passkey } from '../types'

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

// --- change email ------------------------------------------------------
const newEmail = 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)
    changeMessage.value = `Confirmation link sent to ${pending_email}. Your address changes once you open it.`
    newEmail.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
  }
}

// --- passkeys ------------------------------------------------------------
const supported = passkeysSupported()
const passkeys = ref<Passkey[]>([])
const loadingPasskeys = ref(true)
const passkeysError = ref('')

const newLabel = ref(guessDeviceLabel())
const adding = ref(false)
const addError = ref('')
const removingId = ref<number | null>(null)

function guessDeviceLabel(): string {
  const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent
  if (/iPhone/.test(ua)) return 'iPhone'
  if (/iPad/.test(ua)) return 'iPad'
  if (/Android/.test(ua)) return 'Android device'
  if (/Macintosh/.test(ua)) return 'Mac'
  if (/Windows/.test(ua)) return 'Windows PC'
  if (/Linux/.test(ua)) return 'Linux PC'
  return 'This device'
}

onMounted(loadPasskeys)

async function loadPasskeys() {
  if (!supported) {
    loadingPasskeys.value = false
    return
  }
  loadingPasskeys.value = true
  passkeysError.value = ''
  try {
    const { passkeys: fetched } = await apiRequest<{ passkeys: Passkey[] }>('/passkeys', { auth: true })
    passkeys.value = fetched
  } catch (e) {
    passkeysError.value = e instanceof ApiError ? e.message : 'Could not load your passkeys.'
  } finally {
    loadingPasskeys.value = false
  }
}

async function onAddPasskey() {
  adding.value = true
  addError.value = ''
  try {
    const passkey = await registerPasskey(newLabel.value.trim() || guessDeviceLabel())
    passkeys.value.push(passkey)
    newLabel.value = guessDeviceLabel()
    await auth.fetchMe() // clears the "add a passkey" notice once there's one
  } catch (e) {
    if (e instanceof DOMException && e.name === 'NotAllowedError') {
      addError.value = 'Cancelled.'
    } else {
      addError.value = e instanceof ApiError ? e.message : 'Could not add that passkey.'
    }
  } finally {
    adding.value = false
  }
}

async function onRemovePasskey(passkey: Passkey) {
  removingId.value = passkey.id
  passkeysError.value = ''
  try {
    await apiRequest(`/passkeys/${passkey.id}`, { method: 'DELETE', auth: true })
    passkeys.value = passkeys.value.filter((p) => p.id !== passkey.id)
    await auth.fetchMe() // the notice comes back if that was the last one
  } catch (e) {
    passkeysError.value = e instanceof ApiError ? e.message : 'Could not remove that passkey.'
  } finally {
    removingId.value = null
  }
}
</script>

<template>
  <section class="card">
    <h1>Your profile</h1>

    <p><strong>Email:</strong> {{ auth.user?.email }}</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>
      <h2>Change email address</h2>
      <p class="muted">
        We'll email a confirmation link to the new address; the change only
        takes effect once you open it.
      </p>
      <form class="form" @submit.prevent="onChangeEmail">
        <label>
          <span>New email</span>
          <input v-model="newEmail" class="field" type="email" maxlength="255" required />
          <small v-if="changeError?.fieldError('email')" class="field-error">
            {{ changeError.fieldError('email') }}
          </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>
      <h2>Passkeys</h2>

      <template v-if="!supported">
        <p class="muted">Passkeys aren't supported in this browser.</p>
      </template>

      <template v-else>
        <p class="muted">
          Sign in with your device's fingerprint, face, or PIN instead of an
          email link. You can add more than one, e.g. for a phone and a laptop.
        </p>

        <p v-if="passkeysError" class="form-error">{{ passkeysError }}</p>
        <p v-else-if="loadingPasskeys" class="muted">Loading…</p>
        <p v-else-if="passkeys.length === 0" class="muted">No passkeys yet.</p>

        <ul v-else class="passkeys">
          <li v-for="passkey in passkeys" :key="passkey.id" class="passkeys__item">
            <div class="passkeys__info">
              <span class="passkeys__label">{{ passkey.label }}</span>
              <span class="passkeys__meta muted">
                {{ passkey.last_used_at ? `Last used ${new Date(passkey.last_used_at).toLocaleDateString()}` : 'Never used' }}
              </span>
            </div>
            <button
              type="button"
              class="passkeys__remove"
              :disabled="removingId === passkey.id"
              @click="onRemovePasskey(passkey)"
            >
              {{ removingId === passkey.id ? 'Removing…' : 'Remove' }}
            </button>
          </li>
        </ul>

        <form class="form form--new-card" @submit.prevent="onAddPasskey">
          <label>
            <span>Label</span>
            <input v-model="newLabel" class="field" type="text" maxlength="100" />
          </label>
          <p v-if="addError" class="form-error">{{ addError }}</p>
          <button type="submit" :disabled="adding">
            {{ adding ? 'Waiting for your passkey…' : 'Add a passkey' }}
          </button>
        </form>
      </template>
    </section>
  </section>
</template>
