import { ref } from 'vue'

export interface Notification {
  id: string
  title: string
  message: string
  type: 'info' | 'success' | 'warning' | 'error'
  timestamp: Date
  read: boolean
  projectId?: number
  userId?: number
}

class NotificationService {
  private notifications = ref<Notification[]>([])
  private listeners: ((notification: Notification) => void)[] = []

  constructor() {
    // Listen for technical specs updates
    window.addEventListener('technical-specs-updated', (event: any) => {
      this.addNotification({
        title: 'Technical Specifications Updated',
        message: 'Project technical requirements have been updated',
        type: 'info',
        projectId: event.detail.projectId
      })
    })
  }

  addNotification(notification: Omit<Notification, 'id' | 'timestamp' | 'read'>) {
    const newNotification: Notification = {
      ...notification,
      id: Date.now().toString(),
      timestamp: new Date(),
      read: false
    }

    this.notifications.value.unshift(newNotification)
    
    // Notify listeners
    this.listeners.forEach(listener => listener(newNotification))

    // Auto-remove after 10 seconds for non-error notifications
    if (notification.type !== 'error') {
      setTimeout(() => {
        this.removeNotification(newNotification.id)
      }, 10000)
    }

    return newNotification.id
  }

  removeNotification(id: string) {
    const index = this.notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      this.notifications.value.splice(index, 1)
    }
  }

  markAsRead(id: string) {
    const notification = this.notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
    }
  }

  markAllAsRead() {
    this.notifications.value.forEach(n => n.read = true)
  }

  getNotifications() {
    return this.notifications.value
  }

  getUnreadCount() {
    return this.notifications.value.filter(n => !n.read).length
  }

  onNotification(callback: (notification: Notification) => void) {
    this.listeners.push(callback)
    
    // Return unsubscribe function
    return () => {
      const index = this.listeners.indexOf(callback)
      if (index > -1) {
        this.listeners.splice(index, 1)
      }
    }
  }

  // Simulate project member notifications for technical specs updates
  notifyProjectMembers(projectId: number, message: string) {
    this.addNotification({
      title: 'Project Update',
      message,
      type: 'info',
      projectId
    })
  }
}

export const notificationService = new NotificationService()