<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuth } from './composables/useAuth'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'

const props = defineProps<{
  mfaToken: string
  onSuccess?: () => void
  onCancel?: () => void
}>()

const { verifyMfa, isLoading, error } = useAuth()

const code = ref('')
const codeInput = ref<HTMLInputElement | null>(null)

const isFormValid = computed(() => {
  return code.value.length === 6 && /^\d+$/.test(code.value)
})

onMounted(() => {
  // Focus the input on mount
  codeInput.value?.focus()
})

function handleInput(event: Event) {
  const input = event.target as HTMLInputElement
  // Only allow digits
  input.value = input.value.replace(/\D/g, '').slice(0, 6)
  code.value = input.value

  // Auto-submit when 6 digits entered
  if (code.value.length === 6) {
    handleSubmit()
  }
}

async function handleSubmit() {
  if (!isFormValid.value) return

  const result = await verifyMfa({
    mfa_token: props.mfaToken,
    code: code.value,
  })

  if (result.access_token) {
    props.onSuccess?.()
  }
}
</script>

<template>
  <Card class="w-full max-w-md">
    <CardHeader class="space-y-1">
      <CardTitle class="text-2xl font-bold">Two-factor authentication</CardTitle>
      <CardDescription>
        Enter the 6-digit code from your authenticator app
      </CardDescription>
    </CardHeader>
    <form @submit.prevent="handleSubmit">
      <CardContent class="space-y-4">
        <Alert v-if="error" variant="destructive">
          <AlertDescription>\{{ error }}</AlertDescription>
        </Alert>

        <div class="space-y-2">
          <Label for="code">Verification Code</Label>
          <Input
            id="code"
            ref="codeInput"
            v-model="code"
            type="text"
            inputmode="numeric"
            pattern="[0-9]*"
            maxlength="6"
            placeholder="000000"
            autocomplete="one-time-code"
            class="text-center text-2xl tracking-widest"
            @input="handleInput"
          />
          <p class="text-sm text-muted-foreground text-center">
            Enter the code from your authenticator app
          </p>
        </div>
      </CardContent>

      <CardFooter class="flex flex-col space-y-2">
        <Button
          type="submit"
          class="w-full"
          :disabled="!isFormValid || isLoading"
        >
          <span v-if="isLoading">Verifying...</span>
          <span v-else>Verify</span>
        </Button>

        <Button
          v-if="onCancel"
          type="button"
          variant="ghost"
          class="w-full"
          @click="onCancel"
        >
          Use a different method
        </Button>
      </CardFooter>
    </form>
  </Card>
</template>
