<script setup lang="ts">
const { t } = useI18n()
const { apiCall, extractData } = useApiClient()
const log = useLogger('Notify All')

const message = ref('')
const url = ref('/dashboard')
const isSending = ref(false)
const lastResult = ref<{
  sentCount: number
  failedCount: number
  totalUsers: number
} | null>(null)

const { cardStatus, showStatus } = useCardStatus()

definePageMeta({
  middleware: 'super-admin'
})

const sendNotification = async () => {
  if (!message.value.trim()) {
    showStatus(t('admin.notifyAllPage.toast.error'), t('admin.notifyAllPage.toast.errorEmptyMessage'), 'error')
    return
  }

  if (message.value.length > 1000) {
    showStatus(t('admin.notifyAllPage.toast.error'), t('admin.notifyAllPage.toast.errorMessageTooLong'), 'error')
    return
  }

  isSending.value = true
  lastResult.value = null

  try {
    const response = await apiCall<{
      success: boolean
      sentCount: number
      failedCount: number
      totalUsers: number
    }>('/api/super-admin/notify-all', {
      method: 'POST',
      body: {
        message: message.value.trim(),
        url: url.value || '/dashboard'
      }
    })

    const data = extractData(response)
    lastResult.value = data

    const failedText = data.failedCount > 0 ? ` (${data.failedCount} failed)` : ''
    showStatus(t('admin.notifyAllPage.toast.success'), t('admin.notifyAllPage.toast.successDescription', {
      sentCount: data.sentCount,
      totalUsers: data.totalUsers,
      failed: failedText
    }), 'success')

    // Clear the message after successful send
    message.value = ''
  } catch (error) {
    log.error('Failed to send notification:', error)
    showStatus(t('admin.notifyAllPage.toast.error'), error instanceof Error ? error.message : t('admin.notifyAllPage.toast.errorSendFailed'), 'error')
  } finally {
    isSending.value = false
  }
}

const characterCount = computed(() => message.value.length)
const canSend = computed(() => message.value.trim().length > 0 && message.value.length <= 1000 && !isSending.value)
</script>

<template>
  <NuxtLayout
    :page-title="t('admin.notify-all')"
    :parent="{
      label: t('admin.title'),
      to: '/dashboard/admin'
    }"
    name="dashboard"
    type="admin"
  >
    <UPageBody>
      <PageMainCard
        :title="t('admin.notify-all')"
        :description="t('admin.notifyAllPage.description')"
        :icon="useSolarIcon('bell')"
        :loading="isSending"
        :show-refresh-button="false"
        :status="cardStatus"
        @update:status="cardStatus = $event"
      >
        <div>
          <label
            for="message"
            class="block text-sm font-medium mb-2"
          >
            {{ t('admin.notifyAllPage.messageLabel') }}
          </label>
          <UTextarea
            id="message"
            v-model="message"
            :placeholder="t('admin.notifyAllPage.messagePlaceholder')"
            :rows="6"
            :maxlength="1000"
            :disabled="isSending"
            class="w-full"
          />
          <div class="flex items-center justify-between mt-1">
            <p class="text-xs text-muted">
              {{ characterCount }} / 1000 {{ t('admin.notifyAllPage.characters') }}
            </p>
            <p
              v-if="characterCount > 1000"
              class="text-xs text-red-500"
            >
              {{ t('admin.notifyAllPage.messageTooLong') }}
            </p>
          </div>
        </div>

        <div>
          <label
            for="url"
            class="block text-sm font-medium mb-2"
          >
            {{ t('admin.notifyAllPage.urlLabel') }}
          </label>
          <UInput
            id="url"
            v-model="url"
            placeholder="/dashboard"
            :disabled="isSending"
            class="w-full"
          />
          <p class="text-xs text-muted mt-1">
            {{ t('admin.notifyAllPage.urlDescription') }}
          </p>
        </div>

        <div class="flex items-center gap-4" />

        <UAlert
          v-if="lastResult && lastResult.failedCount > 0"
          color="warning"
          variant="soft"
          icon="lucide:alert-triangle"
          :title="t('admin.notifyAllPage.alertTitle')"
          :description="t('admin.notifyAllPage.alertDescription', { failedCount: lastResult.failedCount })"
        />
        <template #footer-actions>
          <UButton
            :disabled="!canSend"
            :loading="isSending"
            color="primary"
            icon="lucide:send"
            @click="sendNotification"
          >
            {{ isSending ? t('admin.notifyAllPage.sending') : t('admin.notifyAllPage.sendButton') }}
          </UButton>
        </template>
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>
