<template>
  <Popover v-model:open="isOpen">
    <PopoverTrigger as-child>
      <Button variant="ghost" size="icon" class="relative">
        <Bell class="h-5 w-5" />
        <span v-if="unreadCount > 0" class="absolute -top-1 -right-1 h-5 w-5 rounded-full bg-red-500 text-white text-xs flex items-center justify-center">
          {{ unreadCount > 99 ? '99+' : unreadCount }}
        </span>
      </Button>
    </PopoverTrigger>
    <PopoverContent class="w-96 p-0" align="end">
      <div class="flex items-center justify-between p-4 border-b">
        <h3 class="font-semibold">Notifications</h3>
        <div class="flex items-center gap-2">
          <Button
            v-if="unreadCount > 0"
            variant="ghost"
            size="sm"
            @click="handleMarkAllRead"
          >
            Mark all read
          </Button>
          <Button
            variant="ghost"
            size="icon"
            @click="handleRefresh"
            :disabled="loading"
          >
            <RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" />
          </Button>
        </div>
      </div>

      <ScrollArea class="h-[400px]">
        <div v-if="loading && notifications.length === 0" class="p-8 text-center text-muted-foreground">
          Loading notifications...
        </div>

        <div v-else-if="notifications.length === 0" class="p-8 text-center text-muted-foreground">
          <Bell class="h-12 w-12 mx-auto mb-2 opacity-50" />
          <p>No notifications</p>
        </div>

        <div v-else class="divide-y">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="p-4 hover:bg-accent cursor-pointer transition-colors"
            :class="{ 'bg-accent/50': !notification.read }"
            @click="handleNotificationClick(notification)"
          >
            <div class="flex items-start gap-3">
              <div class="flex-shrink-0 mt-1">
                <component
                  :is="getNotificationIcon(notification.type)"
                  class="h-5 w-5"
                  :class="getNotificationColor(notification.priority)"
                />
              </div>
              
              <div class="flex-1 min-w-0">
                <div class="flex items-start justify-between gap-2">
                  <p class="font-medium text-sm" :class="{ 'font-semibold': !notification.read }">
                    {{ notification.title }}
                  </p>
                  <Button
                    variant="ghost"
                    size="icon"
                    class="h-6 w-6 flex-shrink-0"
                    @click.stop="handleDelete(notification.id)"
                  >
                    <X class="h-3 w-3" />
                  </Button>
                </div>
                
                <p class="text-sm text-muted-foreground mt-1 line-clamp-2">
                  {{ notification.message }}
                </p>
                
                <p class="text-xs text-muted-foreground mt-2">
                  {{ formatTime(notification.created_at) }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </ScrollArea>

      <div class="p-2 border-t">
        <Button
          variant="ghost"
          class="w-full"
          @click="handleViewAll"
        >
          View all notifications
        </Button>
      </div>
    </PopoverContent>
  </Popover>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useNotificationsStore } from '@/stores/notifications'
import { useToast } from '@/components/ui/toast/use-toast'
import { Button } from '@/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Bell,
  CheckCircle,
  AlertCircle,
  FileText,
  Clock,
  MessageSquare,
  RefreshCw,
  X
} from 'lucide-vue-next'
import type { Notification } from '@/types/notification'
import { NotificationType, NotificationPriority } from '@/types/notification'

const router = useRouter()
const notificationsStore = useNotificationsStore()
const { toast } = useToast()

const isOpen = ref(false)
const loading = ref(false)

const notifications = computed(() => notificationsStore.notifications)
const unreadCount = computed(() => notificationsStore.unreadCount)

let stopPolling: (() => void) | null = null

onMounted(async () => {
  await loadNotifications()
  await notificationsStore.fetchStats()
  
  // Start polling for new notifications every 30 seconds
  stopPolling = notificationsStore.startPolling(30000)
})

onUnmounted(() => {
  if (stopPolling) {
    stopPolling()
  }
})

async function loadNotifications() {
  loading.value = true
  try {
    await notificationsStore.fetchNotifications()
  } catch (error) {
    console.error('Failed to load notifications:', error)
  } finally {
    loading.value = false
  }
}

async function handleRefresh() {
  await loadNotifications()
  await notificationsStore.fetchStats()
}

async function handleMarkAllRead() {
  try {
    await notificationsStore.markAllAsRead()
    toast({
      title: 'Success',
      description: 'All notifications marked as read'
    })
  } catch (error) {
    toast({
      variant: 'destructive',
      title: 'Error',
      description: 'Failed to mark notifications as read'
    })
  }
}

async function handleNotificationClick(notification: Notification) {
  // Mark as read
  if (!notification.read) {
    await notificationsStore.markAsRead([notification.id])
  }

  // Navigate to relevant page
  if (notification.task_id) {
    router.push(`/tasks?taskId=${notification.task_id}`)
  } else if (notification.project_id) {
    router.push(`/projects/${notification.project_id}`)
  }

  isOpen.value = false
}

async function handleDelete(notificationId: number) {
  try {
    await notificationsStore.deleteNotification(notificationId)
  } catch (error) {
    toast({
      variant: 'destructive',
      title: 'Error',
      description: 'Failed to delete notification'
    })
  }
}

function handleViewAll() {
  router.push('/notifications')
  isOpen.value = false
}

function getNotificationIcon(type: NotificationType) {
  switch (type) {
    case NotificationType.TASK_ASSIGNED:
      return FileText
    case NotificationType.TASK_STATUS_CHANGED:
      return CheckCircle
    case NotificationType.SUBMISSION_REVIEWED:
      return CheckCircle
    case NotificationType.WORK_SUBMITTED:
      return FileText
    case NotificationType.DEADLINE_APPROACHING:
      return Clock
    case NotificationType.PROJECT_UPDATE:
      return AlertCircle
    case NotificationType.COMMENT_ADDED:
      return MessageSquare
    default:
      return Bell
  }
}

function getNotificationColor(priority: NotificationPriority) {
  switch (priority) {
    case NotificationPriority.URGENT:
      return 'text-red-500'
    case NotificationPriority.HIGH:
      return 'text-orange-500'
    case NotificationPriority.NORMAL:
      return 'text-blue-500'
    case NotificationPriority.LOW:
      return 'text-gray-500'
    default:
      return 'text-blue-500'
  }
}

function formatTime(timestamp: string): string {
  const date = new Date(timestamp)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return 'Just now'
  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 7) return `${diffDays}d ago`
  
  return date.toLocaleDateString()
}
</script>
