<script setup lang="ts">
import { useForm } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import AuthLayout from '@/layouts/AuthLayout.vue'

const usingRecoveryCode = ref(false)
const form = useForm({
  code: '',
  recovery_code: '',
})

const error = computed(() => form.errors.code || form.errors.recovery_code)

function submit() {
  form
    .transform(data => usingRecoveryCode.value
      ? { code: '', recovery_code: data.recovery_code }
      : { code: data.code, recovery_code: '' })
    .post('/two-factor-challenge', {
      onFinish: () => form.reset(),
    })
}
</script>

<template>
  <AuthLayout>
    <div class="space-y-6">
      <div class="text-center space-y-2">
        <UIcon name="i-lucide-shield-check" class="text-primary size-10" />
        <h1 class="text-xl font-semibold">
          Two-factor authentication
        </h1>
        <p class="text-muted text-sm">
          {{ usingRecoveryCode
            ? 'Enter one of your recovery codes to finish signing in.'
            : 'Enter the six-digit code from your authenticator app.' }}
        </p>
      </div>

      <form class="space-y-4" @submit.prevent="submit">
        <UFormField
          v-if="!usingRecoveryCode"
          label="Authentication code"
          name="code"
          :error="form.errors.code"
        >
          <UInput
            v-model="form.code"
            inputmode="numeric"
            autocomplete="one-time-code"
            maxlength="6"
            placeholder="123456"
            autofocus
            class="w-full"
          />
        </UFormField>

        <UFormField
          v-else
          label="Recovery code"
          name="recovery_code"
          :error="form.errors.recovery_code"
        >
          <UInput
            v-model="form.recovery_code"
            autocomplete="one-time-code"
            placeholder="xxxxx-xxxxx"
            autofocus
            class="w-full"
          />
        </UFormField>

        <UAlert
          v-if="error"
          color="error"
          icon="i-lucide-alert-circle"
          :title="error"
        />

        <UButton type="submit" block :loading="form.processing">
          Verify and sign in
        </UButton>
      </form>

      <div class="text-center">
        <UButton
          variant="link"
          size="sm"
          @click="usingRecoveryCode = !usingRecoveryCode; form.clearErrors(); form.reset()"
        >
          {{ usingRecoveryCode ? 'Use an authentication code' : 'Use a recovery code' }}
        </UButton>
      </div>
    </div>
  </AuthLayout>
</template>
