<template>
  <div v-if="shouldShowPrompt" class="bg-card border rounded-lg p-4 mb-4">
    <div class="flex items-start gap-3">
      <Bell class="h-5 w-5 text-primary mt-0.5" />
      <div class="flex-1">
        <h3 class="font-semibold text-sm mb-1">
          Enable Admin Notifications
        </h3>
        <p class="text-sm text-muted-foreground mb-3">
          Get instant notifications for important admin announcements, even when the app is closed.
        </p>
        
        <div class="flex gap-2">
          <Button 
            @click="enableNotifications" 
            :disabled="isLoading"
            size="sm"
            class="text-xs"
          >
            <Bell class="h-3 w-3 mr-1" />
            {{ isLoading ? 'Enabling...' : 'Enable Notifications' }}
          </Button>
          
          <Button 
            @click="dismiss" 
            variant="outline" 
            size="sm"
            class="text-xs"
          >
            Not Now
          </Button>
        </div>
      </div>
      
      <Button 
        @click="dismiss" 
        variant="ghost" 
        size="icon"
        class="h-6 w-6"
      >
        <X class="h-3 w-3" />
      </Button>
    </div>
  </div>

  <!-- Status indicator when notifications are enabled -->
  <div v-else-if="isSubscribed" class="bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg p-3 mb-4">
    <div class="flex items-center gap-2">
      <BellRing class="h-4 w-4 text-green-600 dark:text-green-400" />
      <span class="text-sm text-green-800 dark:text-green-200">
        Push notifications enabled for admin announcements
      </span>
      <Button 
        @click="disableNotifications"
        variant="ghost" 
        size="sm"
        class="ml-auto text-xs text-green-700 dark:text-green-300 hover:text-green-900 dark:hover:text-green-100"
      >
        Disable
      </Button>
    </div>
  </div>

  <!-- Error state -->
  <div v-if="error" class="bg-destructive/10 border border-destructive/20 rounded-lg p-3 mb-4">
    <div class="flex items-center gap-2">
      <AlertCircle class="h-4 w-4 text-destructive" />
      <span class="text-sm text-destructive">
        {{ error }}
      </span>
      <Button 
        @click="clearError"
        variant="ghost" 
        size="sm"
        class="ml-auto text-xs"
      >
        Dismiss
      </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Button } from '@/components/ui/button'
import { Bell, BellRing, X, AlertCircle } from 'lucide-vue-next'
import { pushService } from '@/lib/notifications/push'
import { configUtils } from '@/lib/config'
import { toast } from 'vue-sonner'

const shouldShowPrompt = ref(false)
const isSubscribed = ref(false)
const isLoading = ref(false)
const error = ref('')
const dismissed = ref(false)

const props = defineProps<{
  autoShow?: boolean
}>()

onMounted(async () => {
  await checkNotificationStatus()
  
  // Show prompt automatically if configured and not dismissed
  if (props.autoShow && !dismissed.value) {
    shouldShowPrompt.value = !isSubscribed.value && 
                               pushService.isSupported() && 
                               configUtils.hasPushConfig() &&
                               pushService.getPermission() !== 'denied'
  }
})

async function checkNotificationStatus() {
  try {
    if (!pushService.isSupported() || !configUtils.hasPushConfig()) {
      return
    }

    isSubscribed.value = await pushService.isSubscribed()
  } catch (err) {
    console.error('Failed to check notification status:', err)
  }
}

async function enableNotifications() {
  try {
    isLoading.value = true
    error.value = ''

    if (!pushService.isSupported()) {
      throw new Error('Push notifications are not supported by your browser')
    }

    if (!configUtils.hasPushConfig()) {
      throw new Error('Push notifications are not configured')
    }

    const subscription = await pushService.subscribe()
    console.log('Push subscription created:', subscription)
    
    // Here you would typically send the subscription to your backend
    // For now, we'll just store it locally and show success
    
    isSubscribed.value = true
    shouldShowPrompt.value = false
    toast.success('Push notifications enabled! You\'ll receive admin announcements even when the app is closed.')

    // TODO: Send subscription to backend
    // await sendSubscriptionToBackend(subscription)

  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to enable notifications'
    error.value = message
    toast.error(message)
  } finally {
    isLoading.value = false
  }
}

async function disableNotifications() {
  try {
    await pushService.unsubscribe()
    isSubscribed.value = false
    toast.success('Push notifications disabled')
    
    // TODO: Remove subscription from backend
    // await removeSubscriptionFromBackend()
    
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to disable notifications'
    error.value = message
    toast.error(message)
  }
}

function dismiss() {
  shouldShowPrompt.value = false
  dismissed.value = true
  
  // Store dismissal in localStorage
  localStorage.setItem('notification-prompt-dismissed', Date.now().toString())
}

function clearError() {
  error.value = ''
}

// Test notification function (for development)
async function testNotification() {
  try {
    await pushService.showLocalNotification({
      title: '🚨 Test Admin Announcement',
      body: 'This is a test notification to verify push notifications are working correctly.',
      icon: '/pwa-192x192.png',
      tag: 'test-notification',
      data: {
        url: '/',
        type: 'admin-announcement'
      }
    })
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to show test notification'
    toast.error(message)
  }
}

// Expose test function for development
defineExpose({
  testNotification,
  enableNotifications,
  disableNotifications
})
</script>