<script setup lang="ts">
import { usePusherBeams } from '../../../composables/usePusherBeams'

const { t } = useI18n()
const { user } = useAuth()
const { sendNotification } = useNotifications()
const toast = useToast()
const pusherBeams = usePusherBeams()
const runtimeConfig = useRuntimeConfig()

const sendingTest = ref(false)

// Check if push notifications are enabled
const saasConfig = runtimeConfig.public.saas as { enablePushNotifications?: boolean } | undefined
const pushNotificationsEnabled = saasConfig?.enablePushNotifications === true

// Check if on native platform
const isNative = ref(false)
const beamsDeviceId = ref<string | null>(null)

onMounted(async () => {
  if (pushNotificationsEnabled) {
    try {
      const capacitor = useCapacitor()
      isNative.value = capacitor?.isCapacitor?.value === true
    } catch {
      isNative.value = false
    }

    // Get device ID if initialized
    if (pusherBeams.isInitialized.value) {
      beamsDeviceId.value = await pusherBeams.getDeviceId()
    }
  }
})

const sendTestNotification = async () => {
  if (!user.value?.id) return

  sendingTest.value = true
  try {
    await sendNotification({
      targetUserId: user.value.id,
      body: t('dashboard.infoPage.notifications.body'),
      url: '/dashboard'
    })

    toast.add({
      title: t('dashboard.infoPage.notifications.toast.successTitle'),
      description: t('dashboard.infoPage.notifications.toast.successDescription'),
      color: 'primary'
    })
  } catch {
    toast.add({
      title: t('dashboard.infoPage.notifications.toast.errorTitle'),
      description: t('dashboard.infoPage.notifications.toast.errorDescription'),
      color: 'error'
    })
  } finally {
    sendingTest.value = false
  }
}

// Push notification test
const sendingPushNotification = ref(false)

async function sendTestPushNotification() {
  sendingPushNotification.value = true
  try {
    const result = await $fetch('/api/push/test', {
      method: 'POST'
    }) as { publishId?: string }
    toast.add({
      title: 'Push Notification Sent',
      description: `Publish ID: ${result.publishId}`,
      color: 'success'
    })
  } catch (error: unknown) {
    const err = error as { data?: { statusMessage?: string }, message?: string }
    toast.add({
      title: 'Failed to send push notification',
      description: err?.data?.statusMessage || err?.message || 'Unknown error',
      color: 'error'
    })
  } finally {
    sendingPushNotification.value = false
  }
}

// Re-initialize Pusher Beams manually
const reinitializing = ref(false)
async function reinitializePusherBeams() {
  reinitializing.value = true
  try {
    const instanceId = runtimeConfig.public.pusherBeamsInstanceId as string
    if (!instanceId) {
      toast.add({ title: 'No Pusher Beams instance ID configured', color: 'error' })
      return
    }

    await pusherBeams.clearState()
    const initSuccess = await pusherBeams.initialize(instanceId)
    if (!initSuccess) {
      toast.add({ title: 'Failed to initialize Pusher Beams', color: 'error' })
      return
    }

    if (user.value?.id) {
      const userSuccess = await pusherBeams.setUser(user.value.id)
      if (userSuccess) {
        toast.add({ title: 'Pusher Beams re-initialized and user set', color: 'success' })
        beamsDeviceId.value = await pusherBeams.getDeviceId()
      } else {
        toast.add({ title: 'Initialized but failed to set user', color: 'warning' })
      }
    } else {
      toast.add({ title: 'Pusher Beams initialized (no user)', color: 'success' })
    }
  } catch (error: unknown) {
    const err = error as { message?: string }
    toast.add({
      title: 'Error re-initializing',
      description: err?.message || 'Unknown error',
      color: 'error'
    })
  } finally {
    reinitializing.value = false
  }
}
</script>

<template>
  <NuxtLayout
    :page-title="t('dashboard.info')"
    name="dashboard"
    type="admin"
  >
    <UPageBody>
      <PageMainCard
        :title="t('dashboard.info')"
        :description="t('dashboard.infoDescription')"
        :icon="useSolarIcon('info-circle')"
        :show-refresh-button="false"
      >
        <UPageGrid>
          <UCard>
            <template #header>
              <h3 class="text-lg font-medium">
                {{ t('dashboard.infoPage.packageVersions') }}
              </h3>
            </template>
            <div class="columns-2 gap-4 text-base text-muted ">
              <div>{{ t('dashboard.infoPage.harmonicSaaS') }}</div>
              <div>{{ t('dashboard.infoPage.nuxt') }}</div>
              <div>v{{ runtimeConfig.public.harmonicSaaSVersion }}</div>
              <div>v{{ runtimeConfig.public.nuxtVersion }}</div>
            </div>
          </UCard>
          <UCard>
            <template #header>
              <h3 class="text-lg font-medium">
                {{ t('dashboard.infoPage.notifications.title') }}
              </h3>
            </template>

            <div class="flex flex-col gap-4">
              <div>
                <p class="text-base text-muted mb-4">
                  {{ t('dashboard.infoPage.notifications.description') }}
                </p>
                <UButton
                  color="primary"
                  :loading="sendingTest"
                  @click="sendTestNotification"
                >
                  {{ t('dashboard.infoPage.notifications.sendTest') }}
                </UButton>
              </div>
            </div>
          </UCard>

          <!-- Push Notifications Section (only shown when enabled) -->
          <UCard v-if="pushNotificationsEnabled">
            <template #header>
              <h3 class="text-lg font-medium">
                Push Notifications (Pusher Beams)
              </h3>
            </template>

            <div class="space-y-4">
              <!-- Status -->
              <div class="grid grid-cols-2 gap-2 text-sm">
                <div class="text-muted">
                  Platform:
                </div>
                <div class="font-mono">
                  {{ isNative ? 'Native (Capacitor)' : 'Web' }}
                </div>

                <div class="text-muted">
                  Beams Initialized:
                </div>
                <div>
                  <UBadge :color="pusherBeams.isInitialized.value ? 'success' : 'error'">
                    {{ pusherBeams.isInitialized.value ? 'Yes' : 'No' }}
                  </UBadge>
                </div>

                <div class="text-muted">
                  User ID:
                </div>
                <div class="font-mono text-xs break-all">
                  {{ user?.id || 'Not logged in' }}
                </div>

                <div class="text-muted">
                  Device ID:
                </div>
                <div class="font-mono text-xs break-all">
                  {{ beamsDeviceId || 'Not available' }}
                </div>

                <template v-if="pusherBeams.error.value">
                  <div class="text-muted">
                    Error:
                  </div>
                  <div class="text-red-500 text-sm">
                    {{ pusherBeams.error.value }}
                  </div>
                </template>
              </div>

              <!-- Actions -->
              <div class="pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3">
                <div class="flex items-center gap-3">
                  <UButton
                    color="primary"
                    :loading="sendingPushNotification"
                    @click="sendTestPushNotification"
                  >
                    Send Test Push
                  </UButton>
                  <UButton
                    color="neutral"
                    variant="outline"
                    :loading="reinitializing"
                    :disabled="!isNative"
                    @click="reinitializePusherBeams"
                  >
                    Re-initialize Beams
                  </UButton>
                </div>
                <p
                  v-if="!isNative"
                  class="text-xs text-muted"
                >
                  Re-initialize is only available on native platforms
                </p>
              </div>
            </div>
          </UCard>

          <UCard>
            <template #header>
              <h3 class="text-lg font-medium">
                {{ t('dashboard.infoPage.title') }}
              </h3>
            </template>
          </UCard>
        </UPageGrid>
      </PageMainCard>
    </UPageBody>
    <PageStatus />
    <NotificationsSlideover />
  </NuxtLayout>
</template>
