'use client'

import { useQuery } from '@apollo/client'

import { GET_CONVERSATIONS, GET_INCOMING_REQUESTS, GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
import { useRealtime } from '@/hooks/useRealtime'

export function useSidebarData() {
  // Загружаем данные для уведомлений
  const { data: conversationsData, refetch: refetchConversations } = useQuery(GET_CONVERSATIONS, {
    fetchPolicy: 'cache-first',
    errorPolicy: 'ignore',
    notifyOnNetworkStatusChange: false,
  })

  const { data: incomingRequestsData, refetch: refetchIncoming } = useQuery(GET_INCOMING_REQUESTS, {
    fetchPolicy: 'cache-first',
    errorPolicy: 'ignore',
    notifyOnNetworkStatusChange: false,
  })

  const { data: pendingData, refetch: refetchPending } = useQuery(GET_PENDING_SUPPLIES_COUNT, {
    fetchPolicy: 'cache-first',
    errorPolicy: 'ignore',
    notifyOnNetworkStatusChange: false,
  })

  // Реалтайм обновления
  useRealtime({
    onEvent: (evt) => {
      switch (evt.type) {
        case 'message:new':
          refetchConversations()
          break
        case 'counterparty:request:new':
        case 'counterparty:request:updated':
          refetchIncoming()
          break
        case 'supply-order:new':
        case 'supply-order:updated':
          refetchPending()
          break
      }
    },
  })

  // Вычисляем количества
  const conversations = conversationsData?.conversations || []
  const incomingRequests = incomingRequestsData?.incomingRequests || []
  
  const totalUnreadCount = conversations.reduce(
    (sum: number, conv: { unreadCount?: number }) => sum + (conv.unreadCount || 0),
    0,
  )
  const incomingRequestsCount = incomingRequests.length
  const logisticsOrdersCount = pendingData?.pendingSuppliesCount?.logisticsOrders || 0
  const supplyOrdersCount = pendingData?.pendingSuppliesCount?.supplyOrders || 0
  const incomingSupplierOrdersCount = pendingData?.pendingSuppliesCount?.incomingSupplierOrders || 0

  return {
    totalUnreadCount,
    incomingRequestsCount,
    logisticsOrdersCount,
    supplyOrdersCount,
    incomingSupplierOrdersCount,
  }
}