<script setup lang="ts">
const { listUserPasskeys, addPasskey, deletePasskey, user } = useAuth()

const { t } = useI18n()
const { showStatus } = useStatus()

const isAddModalOpen = ref(false)
const passkeyName = ref('')
const loading = ref(false)
const passkeys = ref<Array<{ id: string, name?: string, createdAt: Date }>>([])
const loadingPasskeys = ref(false)
const deletingId = ref<string | null>(null)

// Fetch user's passkeys
async function fetchPasskeys() {
  if (!user.value) return

  loadingPasskeys.value = true
  try {
    const response = await listUserPasskeys() as { data: Array<{ id: string, name?: string, createdAt: Date }> }
    passkeys.value = response.data || []
  } catch (error) {
    showStatus(t('account.passkey.loadFailed'), (error as Error).message, 'error')
  } finally {
    loadingPasskeys.value = false
  }
}

// Add new passkey
async function handleAddPasskey() {
  if (!passkeyName.value || loading.value || !user.value) return

  loading.value = true
  showStatus(t('account.passkey.registering'), '', 'primary')

  try {
    await addPasskey({
      name: passkeyName.value
    })

    showStatus(t('account.passkey.registered'), t('account.passkey.registeredDescription'), 'success')

    // Refresh the list
    await fetchPasskeys()

    // Close modal and reset
    isAddModalOpen.value = false
    passkeyName.value = ''
  } catch (error) {
    showStatus(t('account.passkey.registerFailed'), (error as Error).message, 'error')
  } finally {
    loading.value = false
  }
}

// Delete passkey
async function handleDeletePasskey(passkeyId: string) {
  if (deletingId.value) return

  deletingId.value = passkeyId
  showStatus(t('account.passkey.deleting'), '', 'primary')

  try {
    await deletePasskey({
      id: passkeyId
    })

    showStatus(t('account.passkey.deleted'), '', 'success')

    // Refresh the list
    await fetchPasskeys()
  } catch (error) {
    showStatus(t('account.passkey.deleteFailed'), (error as Error).message, 'error')
  } finally {
    deletingId.value = null
  }
}

// Load passkeys on mount
onMounted(() => {
  fetchPasskeys()
})
</script>

<template>
  <PageMainCard
    :title="t('account.passkey.title')"
    :description="t('account.passkey.description')"
    :icon="useSolarIcon('key')"
    :loading="loadingPasskeys"
    :on-refresh="fetchPasskeys"
  >
    <template #header-actions>
      <UButton
        icon="lucide:plus"
        color="primary"
        :disabled="loadingPasskeys"
        @click="isAddModalOpen = true"
      >
        {{ t('account.passkey.addButton') }}
      </UButton>
    </template>

    <div
      v-if="loadingPasskeys"
      class="flex justify-center py-8"
    >
      <UIcon
        :name="useSolarIcon('loader-2')"
        class="animate-spin h-6 w-6 text-muted"
      />
    </div>

    <div
      v-else-if="passkeys.length === 0"
      class="text-center py-8"
    >
      <UIcon
        :name="useSolarIcon('key')"
        class="h-12 w-12 mx-auto mb-3 opacity-50"
      />
      <p class="text-muted">
        {{ t('account.passkey.noPasskeys') }}
      </p>
    </div>

    <div
      v-else
      class="space-y-3"
    >
      <div
        v-for="passkey in passkeys"
        :key="passkey.id"
        class="flex items-center justify-between p-4 border border-default rounded-lg"
      >
        <div class="flex items-center gap-3">
          <div class="p-2 rounded-lg bg-primary/10">
            <UIcon
              :name="useSolarIcon('key')"
              class="h-5 w-5 text-primary"
            />
          </div>
          <div>
            <p class="font-medium">
              {{ passkey.name || t('account.passkey.unnamedPasskey') }}
            </p>
            <p class="text-sm text-muted">
              {{ t('account.passkey.addedOn', { date: new Date(passkey.createdAt).toLocaleDateString() }) }}
            </p>
          </div>
        </div>
        <UButton
          :icon="useSolarIcon('trash-bin-trash')"
          color="error"
          variant="ghost"
          :loading="deletingId === passkey.id"
          :disabled="deletingId === passkey.id"
          @click="handleDeletePasskey(passkey.id)"
        >
          {{ t('common.delete') }}
        </UButton>
      </div>
    </div>
  </PageMainCard>

  <!-- Add Passkey Modal -->
  <UModal
    v-model:open="isAddModalOpen"
    :title="t('account.passkey.addTitle')"
    :description="t('account.passkey.addDescription')"
  >
    <template #body>
      <form
        class="space-y-4"
        @submit.prevent="handleAddPasskey"
      >
        <UFormField
          :label="t('account.passkey.nameLabel')"
          :hint="t('account.passkey.nameHint')"
        >
          <UInput
            v-model="passkeyName"
            :placeholder="t('account.passkey.namePlaceholder')"
            class="w-full"
            :icon="useSolarIcon('tag')"
          />
        </UFormField>

        <div class="flex justify-end gap-3 pt-4">
          <UButton
            :label="t('common.cancel')"
            variant="ghost"
            color="neutral"
            :disabled="loading"
            @click="isAddModalOpen = false"
          />
          <UButton
            type="submit"
            :label="t('account.passkey.addButton')"
            icon="lucide:plus"
            :loading="loading"
            :disabled="!passkeyName || loading"
          />
        </div>
      </form>
    </template>
  </UModal>
</template>
