import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from 'boot/axios'
import { useProjectsStore } from 'stores/projects'
import { useAuthStore } from 'stores/auth'
import { useChatsStore } from 'stores/chats'
import { useUsersStore } from 'stores/users'
import { useCompaniesStore } from 'stores/companies'

export const useSSEStore = defineStore('sse', () => {
  const eventSource = ref<EventSource | null>(null)
  const isConnected = ref(false)
  const reconnectAttempts = ref(0)
  const maxReconnectAttempts = 5

  const projectsStore = useProjectsStore()
  const authStore = useAuthStore()
  const chatsStore = useChatsStore()
  const usersStore = useUsersStore()
  const companiesStore = useCompaniesStore()

  const currentProjectId = computed(() => projectsStore.currentProjectId)

  const connect = () => {
    try {
      if (eventSource.value) eventSource.value.close()

      const url = api.defaults.baseURL + '/events'
      eventSource.value = new EventSource(url)

      setupEventListeners()
      
      eventSource.value.onopen = () => {
        isConnected.value = true
        reconnectAttempts.value = 0
        console.log('SSE connected')
      }

      eventSource.value.onerror = (error) => {
        console.error('SSE error:', error)
        isConnected.value = false
        
        if (reconnectAttempts.value < maxReconnectAttempts) {
          setTimeout(() => {
            reconnectAttempts.value++
            connect()
          }, 3000 * reconnectAttempts.value)
        }
      }

    } catch (error) {
      console.error('Failed to connect SSE:', error)
    }
  }

  const disconnect = () => {
    if (eventSource.value) {
      eventSource.value.close()
      eventSource.value = null
    }
    isConnected.value = false
    reconnectAttempts.value = 0
  }

  const setupEventListeners = () => {
    if (!eventSource.value) return

    eventSource.value.addEventListener('chat-update', (event) => {
      const data = JSON.parse(event.data)
      authStore.updateProfile().catch(() => {}) // for update count of active chats in subscribe
      projectsStore.init().catch(() => {}) // for update count of chats on projects page
  
      if (data.project_id === currentProjectId.value) {
        chatsStore.init().catch(() => {})
        usersStore.init().catch(() => {}) // for update users from chats
      }
    })

    eventSource.value.addEventListener('chat-delete', (event) => {
      const data = JSON.parse(event.data)
      projectsStore.init().catch(() => {}) // for update count of chats on projects page
      authStore.updateProfile().catch(() => {}) // for update count of active chats in subscribe

      if (data.project_id === currentProjectId.value) {
        chatsStore.init().catch(() => {})
        usersStore.init().catch(() => {}) // for update users from chats
      }
    })

    eventSource.value.addEventListener('user-update', (event) => {
      const data = JSON.parse(event.data)
      if (data.project_id === currentProjectId.value) {
        usersStore.init().catch(() => {})
      }
    })

    eventSource.value.addEventListener('company-update', (event) => {
      const data = JSON.parse(event.data)
      if (data.project_id === currentProjectId.value) {
        usersStore.init().catch(() => {})
        companiesStore.init().catch(() => {})
      }
    })

    eventSource.value.addEventListener('customer-update', () => {
      authStore.updateProfile().catch(() => {})
    })
  }

  const eventSourceComputed = computed(() => eventSource.value)
  const isConnectedComputed = computed(() => isConnected.value)

  return {
    eventSource: eventSourceComputed,
    isConnected: isConnectedComputed,
    connect,
    disconnect
  }
})
