'use client'

import { useQuery } from '@apollo/client'
import { useMemo } from 'react'
import { toast } from 'sonner'

import { GET_MY_SELLER_GOODS_SUPPLY_REQUESTS } from '@/graphql/mutations/seller-goods-v2'
import { GET_LOGISTICS_PARTNERS } from '@/graphql/queries'
import { GET_MY_EMPLOYEES_V2 } from '@/graphql/queries/employees-v2'
import { useAuthContext } from '@/contexts/AuthContext'
import { useRealtime } from '@/hooks/useRealtime'

import type { FulfillmentGoodsSupply, Employee, LogisticsPartner } from '../types/fulfillment-goods.types'

export function useFulfillmentGoodsData() {
  const { user } = useAuthContext()
  
  // Загружаем товарные поставки V2
  const { data: goodsData, loading: goodsLoading, error: goodsError, refetch: refetchGoods } = useQuery(
    GET_MY_SELLER_GOODS_SUPPLY_REQUESTS,
    {
      fetchPolicy: 'cache-and-network',
      errorPolicy: 'all',
    },
  )
  
  // Загружаем сотрудников фулфилмента
  const { data: employeesData } = useQuery(GET_MY_EMPLOYEES_V2)
  
  // Загружаем логистических партнеров
  const { data: logisticsData } = useQuery(GET_LOGISTICS_PARTNERS)
  
  // Realtime уведомления для фулфилмента
  useRealtime({
    onEvent: (evt) => {
      if (evt.type === 'supply-order:new' || evt.type === 'supply-order:updated') {
        // Проверяем что событие касается нашего фулфилмента
        if (evt.payload?.fulfillmentCenterId === user?.organizationId) {
          if (evt.type === 'supply-order:new') {
            toast.info('🆕 Новая товарная поставка от селлера!')
          } else {
            toast.info('📝 Товарная поставка обновлена')
          }
          refetchGoods()
        }
      }
    },
  })
  
  // Фильтруем поставки для текущего фулфилмента
  const fulfillmentSupplies: FulfillmentGoodsSupply[] = useMemo(() => {
    const supplies = goodsData?.mySellerGoodsSupplyRequests || []
    
    return supplies.filter((supply: any) => 
      supply.fulfillmentCenterId === user?.organizationId,
    )
  }, [goodsData, user?.organizationId])
  
  // Группируем по табам
  const groupedSupplies = useMemo(() => {
    return {
      new: fulfillmentSupplies.filter(s => s.status === 'SUPPLIER_APPROVED'),
      receiving: fulfillmentSupplies.filter(s => s.status === 'CONFIRMED'),
      received: fulfillmentSupplies.filter(s => s.status === 'DELIVERED'),
      all: fulfillmentSupplies,
    }
  }, [fulfillmentSupplies])
  
  // Сотрудники и партнеры
  const employees: Employee[] = employeesData?.employeesV2?.items || []
  const logisticsPartners: LogisticsPartner[] = logisticsData?.logisticsPartners || []
  
  return {
    // Данные
    supplies: fulfillmentSupplies,
    groupedSupplies,
    employees,
    logisticsPartners,
    
    // Состояние
    loading: goodsLoading,
    error: goodsError,
    
    // Действия
    refetch: refetchGoods,
  }
}