/**
 * ХУКА ДЛЯ УПРАВЛЕНИЯ УСЛУГАМИ ФУЛФИЛМЕНТА
 *
 * Выделена из direct-supply-creation.tsx
 * Управляет услугами, расходниками и настройками фулфилмента
 */

import { useState, useCallback } from 'react'

import { GET_COUNTERPARTY_SERVICES, GET_COUNTERPARTY_SUPPLIES } from '@/graphql/queries'
import { apolloClient } from '@/lib/apollo-client'

import type { FulfillmentService, UseFulfillmentServicesReturn } from '../types/direct-supply.types'

export function useFulfillmentServices(): UseFulfillmentServicesReturn {
  // Состояния
  const [selectedServices, setSelectedServices] = useState<string[]>([])
  const [selectedConsumables, setSelectedConsumables] = useState<string[]>([])
  const [organizationServices, setOrganizationServices] = useState<{
    [orgId: string]: FulfillmentService[]
  }>({})
  const [organizationSupplies, setOrganizationSupplies] = useState<{
    [orgId: string]: FulfillmentService[]
  }>({})
  const [deliveryDateOriginal, setDeliveryDateOriginal] = useState<Date | undefined>(undefined)
  const [selectedFulfillmentOrg, setSelectedFulfillmentOrg] = useState<string>('')

  // Переключение выбора услуги
  const toggleService = useCallback((serviceId: string) => {
    setSelectedServices((prev) =>
      prev.includes(serviceId) ? prev.filter((id) => id !== serviceId) : [...prev, serviceId],
    )
  }, [])

  // Переключение выбора расходника
  const toggleConsumable = useCallback((consumableId: string) => {
    setSelectedConsumables((prev) =>
      prev.includes(consumableId) ? prev.filter((id) => id !== consumableId) : [...prev, consumableId],
    )
  }, [])

  // Загрузка услуг организации
  const loadOrganizationServices = useCallback(async (orgId: string) => {
    try {
      console.warn('Загружаем услуги для организации:', orgId)

      const { data } = await apolloClient.query({
        query: GET_COUNTERPARTY_SERVICES,
        variables: { counterpartyId: orgId },
        fetchPolicy: 'network-only',
      })

      if (data?.counterpartyServices) {
        setOrganizationServices((prev) => ({
          ...prev,
          [orgId]: data.counterpartyServices,
        }))
        console.warn('Загружены услуги:', data.counterpartyServices)
      }
    } catch (error) {
      console.error('Ошибка загрузки услуг:', error)
    }
  }, [])

  // Загрузка расходников организации
  const loadOrganizationSupplies = useCallback(async (orgId: string) => {
    try {
      console.warn('Загружаем расходники для организации:', orgId)

      const { data } = await apolloClient.query({
        query: GET_COUNTERPARTY_SUPPLIES,
        variables: { counterpartyId: orgId },
        fetchPolicy: 'network-only',
      })

      if (data?.counterpartySupplies) {
        setOrganizationSupplies((prev) => ({
          ...prev,
          [orgId]: data.counterpartySupplies,
        }))
        console.warn('Загружены расходники:', data.counterpartySupplies)
      }
    } catch (error) {
      console.error('Ошибка загрузки расходников:', error)
    }
  }, [])

  // Расчет стоимости услуг
  const getServicesCost = useCallback(
    (totalQuantity: number = 0): number => {
      if (!selectedFulfillmentOrg || selectedServices.length === 0) return 0

      const services = organizationServices[selectedFulfillmentOrg] || []
      return (
        selectedServices.reduce((sum, serviceId) => {
          const service = services.find((s) => s.id === serviceId)
          return sum + (service ? service.price : 0)
        }, 0) * totalQuantity
      )
    },
    [selectedFulfillmentOrg, selectedServices, organizationServices],
  )

  // Расчет стоимости расходников
  const getConsumablesCost = useCallback(
    (totalQuantity: number = 0): number => {
      if (!selectedFulfillmentOrg || selectedConsumables.length === 0) return 0

      const supplies = organizationSupplies[selectedFulfillmentOrg] || []
      return (
        selectedConsumables.reduce((sum, supplyId) => {
          const supply = supplies.find((s) => s.id === supplyId)
          return sum + (supply ? supply.price : 0)
        }, 0) * totalQuantity
      )
    },
    [selectedFulfillmentOrg, selectedConsumables, organizationSupplies],
  )

  return {
    // Состояния
    selectedServices,
    selectedConsumables,
    organizationServices,
    organizationSupplies,
    deliveryDateOriginal,
    selectedFulfillmentOrg,

    // Функции управления
    toggleService,
    toggleConsumable,
    setDeliveryDateOriginal,
    setSelectedFulfillmentOrg,

    // Функции загрузки
    loadOrganizationServices,
    loadOrganizationSupplies,

    // Расчеты
    getServicesCost,
    getConsumablesCost,
  }
}
