<script lang="ts" setup>
import { ref } from 'vue'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { sendVerificationEmail } from '@/modules/auth'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'

const dismissed = ref(false)
const loading = ref(false)
const feedbackMessage = ref('')
const errorMessage = ref('')

const handleSend = async () => {
  loading.value = true
  feedbackMessage.value = ''
  errorMessage.value = ''

  try {
    const response = await sendVerificationEmail()
    feedbackMessage.value = response.message
  } catch (error) {
    errorMessage.value = getApiErrorMessage(error, 'Gagal menghantar pautan pengesahan. Sila cuba lagi.')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <AlertRoot v-if="!dismissed" class="mb-4" variant="primary">
    <AlertTitle>Pengesahan emel diperlukan.</AlertTitle>
    <AlertDescription>
      Sila sahkan emel anda dengan menekan butang di bawah.
      <span v-if="feedbackMessage" class="mt-2 block">{{ feedbackMessage }}</span>
      <span v-if="errorMessage" class="mt-2 block text-danger">{{ errorMessage }}</span>
    </AlertDescription>
    <div class="mt-4 flex flex-wrap gap-2">
      <Button size="sm" variant="primary" look="outline" type="button" :disabled="loading" @click="handleSend">
        {{ loading ? 'Menghantar...' : 'Hantar Pautan Pengesahan' }}
      </Button>
      <Button size="sm" type="button" @click="dismissed = true">
        Abaikan
      </Button>
    </div>
  </AlertRoot>
</template>
