/**
 * Hook для загрузки и управления данными контрагентов
 * Обрабатывает все GraphQL queries и кэширование
 */

import { useQuery } from '@apollo/client'
import { useState, useCallback } from 'react'

import {
  GET_MY_COUNTERPARTIES,
  GET_INCOMING_REQUESTS,
  GET_OUTGOING_REQUESTS,
  SEARCH_ORGANIZATIONS,
} from '@/graphql/queries'
import { GET_MY_PARTNER_LINK } from '@/graphql/referral-queries'

import type { UseCounterpartyDataReturn, Organization, CounterpartyRequest, OrganizationType } from '../types'

export function useCounterpartyData(): UseCounterpartyDataReturn {
  const [searchResults, setSearchResults] = useState<Organization[]>([])
  const [searchLoading, setSearchLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Основные queries
  const {
    data: counterpartiesData,
    loading: counterpartiesLoading,
    refetch: refetchCounterparties,
  } = useQuery(GET_MY_COUNTERPARTIES, {
    errorPolicy: 'all',
    onError: (error) => {
      console.error('Error loading counterparties:', error)
      setError('Ошибка загрузки контрагентов')
    },
  })

  const {
    data: incomingData,
    loading: incomingLoading,
    refetch: refetchIncoming,
  } = useQuery(GET_INCOMING_REQUESTS, {
    errorPolicy: 'all',
    onCompleted: (data) => {
      console.warn('🎯 INCOMING_REQUESTS ФРОНТЕНД:', {
        requestsCount: data?.incomingRequests?.length || 0,
        requests:
          data?.incomingRequests?.map((r: CounterpartyRequest) => ({
            id: r.id,
            senderId: r.sender?.id,
            senderName: r.sender?.name || r.sender?.fullName,
            status: r.status,
          })) || [],
        timestamp: new Date().toISOString(),
      })
    },
    onError: (error) => {
      console.error('❌ Error loading incoming requests:', error)
      setError('Ошибка загрузки входящих заявок')
    },
  })

  const {
    data: outgoingData,
    loading: outgoingLoading,
    refetch: refetchOutgoing,
  } = useQuery(GET_OUTGOING_REQUESTS, {
    errorPolicy: 'all',
    onError: (error) => {
      console.error('Error loading outgoing requests:', error)
      setError('Ошибка загрузки исходящих заявок')
    },
  })

  const {
    data: partnerLinkData,
    loading: partnerLinkLoading,
    refetch: refetchPartnerLink,
  } = useQuery(GET_MY_PARTNER_LINK, {
    errorPolicy: 'all',
    onError: (error) => {
      console.error('Error loading partner link:', error)
      setError('Ошибка загрузки партнерской ссылки')
    },
  })

  // Поиск организаций
  const searchOrganizations = useCallback(async (query: string, type?: OrganizationType) => {
    if (!query.trim()) {
      setSearchResults([])
      return
    }

    setSearchLoading(true)
    setError(null)

    try {
      // Используем Apollo Client напрямую для поиска
      const { apolloClient } = await import('@/lib/apollo-client')

      const variables: { search: string; type?: string } = { search: query }
      if (type && type !== 'all') {
        variables.type = type
      }

      const { data } = await apolloClient.query({
        query: SEARCH_ORGANIZATIONS,
        variables,
        fetchPolicy: 'network-only', // Всегда получать свежие данные поиска
      })

      if (data?.searchOrganizations?.success) {
        setSearchResults(data.searchOrganizations.organizations || [])
      } else {
        setError(data?.searchOrganizations?.message || 'Ошибка поиска организаций')
        setSearchResults([])
      }
    } catch (error) {
      console.error('Search organizations error:', error)
      setError('Ошибка поиска организаций')
      setSearchResults([])
    } finally {
      setSearchLoading(false)
    }
  }, [])

  // Обновление всех данных
  const refetchAll = useCallback(async () => {
    setError(null)

    try {
      await Promise.all([refetchCounterparties(), refetchIncoming(), refetchOutgoing(), refetchPartnerLink()])
    } catch (error) {
      console.error('Error refetching data:', error)
      setError('Ошибка обновления данных')
    }
  }, [refetchCounterparties, refetchIncoming, refetchOutgoing, refetchPartnerLink])

  // Извлечение данных из responses
  const counterparties: Organization[] = counterpartiesData?.myCounterparties || []
  const incomingRequests: CounterpartyRequest[] = incomingData?.incomingRequests || []
  const outgoingRequests: CounterpartyRequest[] = outgoingData?.outgoingRequests || []
  const partnerLink: string | null = partnerLinkData?.myPartnerLink || null

  return {
    // Данные
    counterparties,
    incomingRequests,
    outgoingRequests,
    searchResults,
    partnerLink,

    // Состояние загрузки
    counterpartiesLoading,
    incomingLoading,
    outgoingLoading,
    searchLoading,
    partnerLinkLoading,

    // Ошибки
    error,

    // Методы
    refetchAll,
    searchOrganizations,
  }
}
