import { notificationsApi } from '@/api/notificationsApi'
import { defineStore } from 'pinia'

export const useNotificationsStore = defineStore('notifications', {
  state: () => ({
    notifications: [],
    isLoading: false,
    error: null,
    selectedNotifications: [],
    counts: {
      read: 0,
      unread: 0,
      total: 0
    },
    pagination: {
      currentPage: 1,
      lastPage: 1,
      perPage: 10
    }
  }),

  getters: {
    unreadCount: (state) => state.counts.unread,
    readCount: (state) => state.counts.read,
    totalCount: (state) => state.counts.total,
    newCount: (state) => state.notifications.filter(n => n.isNew).length,
    
    getFilteredNotifications: (state) => (activeTab, searchQuery) => {
      let filtered = state.notifications

      if (searchQuery) {
        filtered = filtered.filter(n => 
          n.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          n.description.toLowerCase().includes(searchQuery.toLowerCase())
        )
      }

      return filtered
    }
  },

  actions: {
    async fetchNotifications(page = 1, perPage = 10, type = 'all') {
      this.isLoading = true
      this.error = null
      try {
        const response = await notificationsApi.getAllNotifications(page, perPage, type)
        const data = response.data.data || {}
        
        if (data.counts) {
          this.counts = {
            read: data.counts.read || 0,
            unread: data.counts.unread || 0,
            total: data.counts.total || 0
          }
        }
        
        // Track API pagination metadata
        if (data.notifications) {
          this.pagination = {
            currentPage: data.notifications.current_page || 1,
            lastPage: data.notifications.last_page || 1,
            perPage: data.notifications.per_page || 10
          }
        }
        
        const items = data.notifications?.data || []
        this.notifications = items.map(item => {
          const title = item.type
            .split('_')
            .map(w => w.charAt(0).toUpperCase() + w.slice(1))
            .join(' ')
          return {
            ...item,
            title,
            description: item.message,
            time: new Date(item.created_at).toLocaleString(),
            isNew: item.status === 'pending' || item.status === 'Update',
            isUnread: item.read === false
          }
        })
      } catch (err) {
        this.error = err.message || 'Failed to fetch notifications'
        console.error('Fetch notifications error:', err)
      } finally {
        this.isLoading = false
      }
    },

    async markAsRead(id) {
      try {
        await notificationsApi.markAsRead(id)
        const index = this.notifications.findIndex(n => n.id === id)
        if (index > -1) {
          const wasUnread = this.notifications[index].isUnread
          this.notifications.splice(index, 1)
          if (wasUnread) {
            this.counts.unread = Math.max(0, this.counts.unread - 1)
            this.counts.read += 1
          }
        }
        const sel = this.selectedNotifications.indexOf(id)
        if (sel > -1) this.selectedNotifications.splice(sel, 1)
      } catch (err) {
        this.error = err.message || 'Failed to mark notification as read'
        console.error('Mark as read error:', err)
      }
    },

    // Bulk mark as read for selected notifications
    async bulkMarkAsRead(notificationIds) {
      // Validate input
      if (!notificationIds || notificationIds.length === 0) {
        console.warn('No notification IDs provided to bulkMarkAsRead')
        return
      }

      // Debug: Log the IDs being sent
      console.log('Bulk marking as read:', notificationIds)
      console.log('Number of IDs:', notificationIds.length)

      this.isLoading = true
      this.error = null
      
      try {
        // Call the bulk API endpoint
        const response = await notificationsApi.bulkMarkAsRead(notificationIds)
        console.log('Bulk mark as read response:', response)
        
        // Optimistically update local state
        let unreadRemoved = 0
        notificationIds.forEach(id => {
          const index = this.notifications.findIndex(n => n.id === id)
          if (index > -1) {
            if (this.notifications[index].isUnread) {
              unreadRemoved++
            }
            // Remove from notifications array
            this.notifications.splice(index, 1)
          }
        })

        // Update counts
        this.counts.unread = Math.max(0, this.counts.unread - unreadRemoved)
        this.counts.read += unreadRemoved
        
        // Clear selections
        this.selectedNotifications = []
      } catch (err) {
        this.error = err.response?.data?.message || err.message || 'Failed to mark notifications as read'
        console.error('Bulk mark as read error:', err)
        console.error('Error response:', err.response?.data)
        throw err
      } finally {
        this.isLoading = false
      }
    },

    // Mark all unread as read using bulk API
    async markAllAsRead() {
      // Get all unread notification IDs
      const unreadIds = this.notifications
        .filter(n => n.isUnread)
        .map(n => n.id)
      
      console.log('Mark all as read - Unread IDs:', unreadIds)
      console.log('Total unread count:', unreadIds.length)
      
      if (unreadIds.length === 0) {
        console.warn('No unread notifications to mark as read')
        return
      }

      await this.bulkMarkAsRead(unreadIds)
    },

    async fetchCount() {
      try {
        const response = await notificationsApi.count()
        this.counts.unread = response.data.data?.unread_count 
        console.log('Unread count:', this.counts.unread)
                             
      } catch (err) {
        this.error = err.message || 'Failed to fetch notification count'
        console.error('Fetch count error:', err)
      }
    },

    async deleteNotification(id) {
      try {
        await notificationsApi.deleteNotification(id)
        const index = this.notifications.findIndex(n => n.id === id)
        if (index > -1) {
          const notification = this.notifications[index]
          if (notification.isUnread) {
            this.counts.unread = Math.max(0, this.counts.unread - 1)
          } else {
            this.counts.read = Math.max(0, this.counts.read - 1)
          }
          this.counts.total = Math.max(0, this.counts.total - 1)
          
          this.notifications.splice(index, 1)
        }
        const selectedIndex = this.selectedNotifications.indexOf(id)
        if (selectedIndex > -1) {
          this.selectedNotifications.splice(selectedIndex, 1)
        }
      } catch (err) {
        this.error = err.message || 'Failed to delete notification'
        console.error('Delete notification error:', err)
      }
    },

    async clearAll() {
      try {
        await notificationsApi.clearAll()
        this.notifications = []
        this.selectedNotifications = []
        this.counts = {
          read: 0,
          unread: 0,
          total: 0
        }
      } catch (err) {
        this.error = err.message || 'Failed to clear all notifications'
        console.error('Clear all error:', err)
      }
    },

    toggleSelectAll(filteredNotifications) {
      if (this.selectedNotifications.length === filteredNotifications.length) {
        this.selectedNotifications = []
      } else {
        this.selectedNotifications = filteredNotifications.map(n => n.id)
      }
    },

    toggleSelect(id) {
      const index = this.selectedNotifications.indexOf(id)
      if (index > -1) {
        this.selectedNotifications.splice(index, 1)
      } else {
        this.selectedNotifications.push(id)
      }
    },

    // Use bulk API for selected notifications
    async markSelectedAsRead() {
      console.log('Mark selected as read - Selected IDs:', this.selectedNotifications)
      
      if (this.selectedNotifications.length === 0) {
        console.warn('No notifications selected')
        return
      }
      
      await this.bulkMarkAsRead([...this.selectedNotifications])
    },

    async deleteSelected() {
      const ids = [...this.selectedNotifications]
      if (ids.length === 0) return
      this.isLoading = true
      this.error = null
      try {
        await notificationsApi.clearAll(ids)
        // Optimistically update local state and counts
        ids.forEach(id => {
          const index = this.notifications.findIndex(n => n.id === id)
          if (index > -1) {
            const notification = this.notifications[index]
            if (notification.isUnread) {
              this.counts.unread = Math.max(0, this.counts.unread - 1)
            } else {
              this.counts.read = Math.max(0, this.counts.read - 1)
            }
            this.counts.total = Math.max(0, this.counts.total - 1)
            this.notifications.splice(index, 1)
          }
        })
        this.selectedNotifications = []
      } catch (err) {
        this.error = err.response?.data?.message || err.message || 'Failed to delete selected notifications'
        console.error('Bulk delete notifications error:', err)
      } finally {
        this.isLoading = false
      }
    }
  }
})
