import { defineStore } from 'pinia'
import { notificationAPI } from '@/services/notification'
import { ElMessage } from 'element-plus'

export const useNotificationStore = defineStore('notification', {
  state: () => ({
    notifications: [],
    unreadCount: 0,
    loading: false,
    pagination: {
      total: 0,
      page: 1,
      per_page: 20,
      pages: 0
    }
  }),

  getters: {
    unreadNotifications: (state) => {
      return state.notifications.filter(notification => !notification.is_read)
    },
    
    readNotifications: (state) => {
      return state.notifications.filter(notification => notification.is_read)
    },
    
    hasUnreadNotifications: (state) => {
      return state.unreadCount > 0
    }
  },

  actions: {
    /**
     * 獲取通知列表
     * @param {Object} params - 查詢參數
     */
    async fetchNotifications(params = {}) {
      try {
        this.loading = true
        
        const response = await notificationAPI.getNotifications({
          page: this.pagination.page,
          per_page: this.pagination.per_page,
          ...params
        })
        
        if (response.success) {
          this.notifications = response.data.notifications
          this.unreadCount = response.data.unread_count
          this.pagination = {
            ...this.pagination,
            ...response.data.pagination
          }
          
          console.log('📮 [Notification] 通知列表已更新', {
            total: this.pagination.total,
            unread: this.unreadCount
          })
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 獲取通知列表失敗:', error)
        ElMessage.error('獲取通知失敗')
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 標記通知為已讀
     * @param {string} notificationId - 通知ID
     */
    async markAsRead(notificationId) {
      try {
        const response = await notificationAPI.markAsRead(notificationId)
        
        if (response.success) {
          // 更新本地狀態
          const notification = this.notifications.find(n => n.id === notificationId)
          if (notification && !notification.is_read) {
            notification.is_read = true
            notification.read = true
            notification.read_at = new Date().toISOString()
            this.unreadCount = Math.max(0, this.unreadCount - 1)
          }
          
          console.log('✅ [Notification] 通知已標記為已讀:', notificationId)
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 標記已讀失敗:', error)
        ElMessage.error('標記已讀失敗')
        throw error
      }
    },

    /**
     * 標記所有通知為已讀
     */
    async markAllAsRead() {
      try {
        const response = await notificationAPI.markAllAsRead()
        
        if (response.success) {
          // 更新本地狀態
          this.notifications.forEach(notification => {
            if (!notification.is_read) {
              notification.is_read = true
              notification.read = true
              notification.read_at = new Date().toISOString()
            }
          })
          this.unreadCount = 0
          
          console.log('✅ [Notification] 所有通知已標記為已讀')
          ElMessage.success(response.message || '所有通知已標記為已讀')
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 標記全部已讀失敗:', error)
        ElMessage.error('標記全部已讀失敗')
        throw error
      }
    },

    /**
     * 刪除通知
     * @param {string} notificationId - 通知ID
     */
    async deleteNotification(notificationId) {
      try {
        const response = await notificationAPI.deleteNotification(notificationId)
        
        if (response.success) {
          // 從本地狀態移除
          const index = this.notifications.findIndex(n => n.id === notificationId)
          if (index !== -1) {
            const notification = this.notifications[index]
            if (!notification.is_read) {
              this.unreadCount = Math.max(0, this.unreadCount - 1)
            }
            this.notifications.splice(index, 1)
            this.pagination.total = Math.max(0, this.pagination.total - 1)
          }
          
          console.log('🗑️ [Notification] 通知已刪除:', notificationId)
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 刪除通知失敗:', error)
        ElMessage.error('刪除通知失敗')
        throw error
      }
    },

    /**
     * 清空所有已讀通知
     */
    async clearNotifications() {
      try {
        const response = await notificationAPI.clearNotifications()
        
        if (response.success) {
          // 從本地狀態移除已讀通知
          this.notifications = this.notifications.filter(n => !n.is_read)
          this.pagination.total = this.notifications.length
          
          console.log('🧹 [Notification] 已讀通知已清除')
          ElMessage.success(response.message || '已讀通知已清除')
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 清除通知失敗:', error)
        ElMessage.error('清除通知失敗')
        throw error
      }
    },

    /**
     * 添加新通知（用於 WebSocket 推送）
     * @param {Object} notification - 通知數據
     */
    addNotification(notification) {
      // 檢查是否已存在
      const exists = this.notifications.find(n => n.id === notification.id)
      if (!exists) {
        // 添加到列表開頭
        this.notifications.unshift(notification)
        
        // 更新未讀數量
        if (!notification.is_read) {
          this.unreadCount += 1
        }
        
        // 更新總數
        this.pagination.total += 1
        
        console.log('📩 [Notification] 新通知已添加:', notification.title)
        
        // 顯示通知
        ElMessage({
          type: this.getMessageType(notification.type),
          title: notification.title,
          message: notification.message,
          duration: 5000
        })
      }
    },

    /**
     * 更新通知
     * @param {Object} notification - 通知數據
     */
    updateNotification(notification) {
      const index = this.notifications.findIndex(n => n.id === notification.id)
      if (index !== -1) {
        const oldNotification = this.notifications[index]
        
        // 更新未讀數量
        if (oldNotification.is_read !== notification.is_read) {
          if (notification.is_read) {
            this.unreadCount = Math.max(0, this.unreadCount - 1)
          } else {
            this.unreadCount += 1
          }
        }
        
        // 更新通知
        this.notifications[index] = { ...oldNotification, ...notification }
        
        console.log('📝 [Notification] 通知已更新:', notification.id)
      }
    },

    /**
     * 創建測試通知（開發用）
     */
    async createTestNotification() {
      try {
        const response = await notificationAPI.createTestNotification()
        
        if (response.success) {
          // 重新獲取通知列表
          await this.fetchNotifications()
          ElMessage.success('測試通知已創建')
        }
        
        return response
        
      } catch (error) {
        console.error('❌ [Notification] 創建測試通知失敗:', error)
        ElMessage.error('創建測試通知失敗')
        throw error
      }
    },

    /**
     * 設置分頁
     * @param {number} page - 頁碼
     * @param {number} per_page - 每頁數量
     */
    setPagination(page, per_page) {
      this.pagination.page = page
      if (per_page) {
        this.pagination.per_page = per_page
      }
    },

    /**
     * 重置狀態
     */
    reset() {
      this.notifications = []
      this.unreadCount = 0
      this.loading = false
      this.pagination = {
        total: 0,
        page: 1,
        per_page: 20,
        pages: 0
      }
    },

    /**
     * 獲取 ElMessage 類型
     * @param {string} type - 通知類型
     */
    getMessageType(type) {
      const typeMap = {
        'success': 'success',
        'error': 'error',
        'warning': 'warning',
        'info': 'info',
        'system': 'info'
      }
      return typeMap[type] || 'info'
    }
  }
})