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

defineOptions({ layout: AuthLayout })

const useRecovery = ref(false)

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

const submit = (): void => {
  form.post('/two-factor-challenge', {
    onFinish: () => {
      form.code = ''
      form.recovery_code = ''
    },
  })
}

const toggleRecovery = (): void => {
  useRecovery.value = !useRecovery.value
  form.code = ''
  form.recovery_code = ''
  form.clearErrors()
}
</script>

<template>
  <VCardText>
    <h4 class="text-h4 mb-1">
      Two-Factor Authentication
    </h4>
    <p class="mb-0">
      <template v-if="!useRecovery">
        Enter the authentication code from your authenticator app
      </template>
      <template v-else>
        Enter one of your emergency recovery codes
      </template>
    </p>
  </VCardText>

  <VCardText>
    <VForm @submit.prevent="submit">
      <VRow>
        <VCol v-if="!useRecovery" cols="12">
          <VTextField
            v-model="form.code"
            label="Code"
            type="text"
            inputmode="numeric"
            autofocus
            autocomplete="one-time-code"
            placeholder="000000"
            :error-messages="form.errors.code ? [form.errors.code] : []"
          />
        </VCol>

        <VCol v-else cols="12">
          <VTextField
            v-model="form.recovery_code"
            label="Recovery Code"
            type="text"
            autofocus
            placeholder="Enter recovery code"
            :error-messages="form.errors.recovery_code ? [form.errors.recovery_code] : []"
          />
        </VCol>

        <VCol cols="12">
          <VCheckbox
            v-model="form.trust_device"
            label="Trust this device for 30 days"
            hint="Skip two-factor authentication on future logins from this device"
            persistent-hint
            density="comfortable"
          />
        </VCol>

        <VCol cols="12">
          <VBtn
            type="submit"
            block
            :loading="form.processing"
            :disabled="form.processing"
          >
            Verify
          </VBtn>
        </VCol>

        <VCol cols="12">
          <VBtn
            variant="text"
            block
            @click="toggleRecovery"
          >
            {{ useRecovery ? 'Use authentication code' : 'Use a recovery code' }}
          </VBtn>
        </VCol>
      </VRow>
    </VForm>
  </VCardText>
</template>
