/**
 * ХУКА ДЛЯ ЛОГИКИ ПОСТРОЕНИЯ РЕЦЕПТУР
 *
 * Выделена из create-suppliers-supply-page.tsx
 * Управляет рецептурами товаров (услуги ФФ, расходники, WB карточки)
 */

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

import {
  GET_COUNTERPARTY_SERVICES,
  GET_COUNTERPARTY_SUPPLIES,
  GET_AVAILABLE_SUPPLIES_FOR_RECIPE,
} from '@/graphql/queries'

import type {
  ProductRecipe,
  FulfillmentService,
  FulfillmentConsumable,
  SellerConsumable,
  RecipeCostCalculation,
} from '../types/supply-creation.types'

interface UseRecipeBuilderProps {
  selectedFulfillment: string
}

export function useRecipeBuilder({ selectedFulfillment }: UseRecipeBuilderProps) {
  // Состояние рецептур
  const [productRecipes, setProductRecipes] = useState<Record<string, ProductRecipe>>({})

  // Загрузка услуг фулфилмента
  const { data: servicesData } = useQuery(GET_COUNTERPARTY_SERVICES, {
    variables: { organizationId: selectedFulfillment || '' },
    skip: !selectedFulfillment,
    errorPolicy: 'all',
  })

  // Загрузка расходников фулфилмента
  const { data: ffConsumablesData } = useQuery(GET_COUNTERPARTY_SUPPLIES, {
    variables: {
      organizationId: selectedFulfillment || '',
      type: 'CONSUMABLE',
    },
    skip: !selectedFulfillment,
    errorPolicy: 'all',
  })

  // Загрузка расходников селлера
  const { data: sellerConsumablesData } = useQuery(GET_AVAILABLE_SUPPLIES_FOR_RECIPE, {
    variables: { type: 'CONSUMABLE' },
    errorPolicy: 'all',
  })

  // Обработка данных
  const fulfillmentServices: FulfillmentService[] = useMemo(() => {
    try {
      return servicesData?.counterpartyServices || []
    } catch (error) {
      console.warn('❌ Error processing fulfillment services:', error)
      return []
    }
  }, [servicesData])

  const fulfillmentConsumables: FulfillmentConsumable[] = useMemo(() => {
    try {
      return ffConsumablesData?.counterpartySupplies || []
    } catch (error) {
      console.warn('❌ Error processing fulfillment consumables:', error)
      return []
    }
  }, [ffConsumablesData])

  const sellerConsumables: SellerConsumable[] = useMemo(() => {
    try {
      return sellerConsumablesData?.availableSuppliesForRecipe || []
    } catch (error) {
      console.warn('❌ Error processing seller consumables:', error)
      return []
    }
  }, [sellerConsumablesData])

  // Инициализация рецептуры для товара
  const initializeProductRecipe = (productId: string) => {
    if (!productRecipes[productId]) {
      setProductRecipes((prev) => ({
        ...prev,
        [productId]: {
          productId,
          selectedServices: [],
          selectedFFConsumables: [],
          selectedSellerConsumables: [],
          selectedWBCard: undefined,
        },
      }))
    }
  }

  // Переключение услуги фулфилмента
  const toggleService = (productId: string, serviceId: string) => {
    setProductRecipes((prev) => {
      const recipe = prev[productId] || {
        productId,
        selectedServices: [],
        selectedFFConsumables: [],
        selectedSellerConsumables: [],
      }

      const isSelected = recipe.selectedServices.includes(serviceId)

      return {
        ...prev,
        [productId]: {
          ...recipe,
          selectedServices: isSelected
            ? recipe.selectedServices.filter((id) => id !== serviceId)
            : [...recipe.selectedServices, serviceId],
        },
      }
    })
  }

  // Переключение расходников ФФ
  const toggleFFConsumable = (productId: string, consumableId: string) => {
    setProductRecipes((prev) => {
      const recipe = prev[productId] || {
        productId,
        selectedServices: [],
        selectedFFConsumables: [],
        selectedSellerConsumables: [],
      }

      const isSelected = recipe.selectedFFConsumables.includes(consumableId)

      return {
        ...prev,
        [productId]: {
          ...recipe,
          selectedFFConsumables: isSelected
            ? recipe.selectedFFConsumables.filter((id) => id !== consumableId)
            : [...recipe.selectedFFConsumables, consumableId],
        },
      }
    })
  }

  // Переключение расходников селлера
  const toggleSellerConsumable = (productId: string, consumableId: string) => {
    setProductRecipes((prev) => {
      const recipe = prev[productId] || {
        productId,
        selectedServices: [],
        selectedFFConsumables: [],
        selectedSellerConsumables: [],
      }

      const isSelected = recipe.selectedSellerConsumables.includes(consumableId)

      return {
        ...prev,
        [productId]: {
          ...recipe,
          selectedSellerConsumables: isSelected
            ? recipe.selectedSellerConsumables.filter((id) => id !== consumableId)
            : [...recipe.selectedSellerConsumables, consumableId],
        },
      }
    })
  }

  // Установка WB карточки
  const setWBCard = (productId: string, cardId: string) => {
    setProductRecipes((prev) => ({
      ...prev,
      [productId]: {
        ...prev[productId],
        selectedWBCard: cardId === 'none' ? undefined : cardId,
      },
    }))
  }

  // Расчет стоимости рецептуры
  const calculateRecipeCost = (productId: string): RecipeCostCalculation => {
    const recipe = productRecipes[productId]
    if (!recipe) return { services: 0, consumables: 0, total: 0 }

    // Стоимость услуг
    const servicesTotal = recipe.selectedServices.reduce((sum, serviceId) => {
      const service = fulfillmentServices.find((s) => s.id === serviceId)
      return sum + (service ? service.price : 0)
    }, 0)

    // Стоимость расходников ФФ
    const ffConsumablesTotal = recipe.selectedFFConsumables.reduce((sum, consumableId) => {
      const consumable = fulfillmentConsumables.find((c) => c.id === consumableId)
      return sum + (consumable ? consumable.price : 0)
    }, 0)

    // Стоимость расходников селлера
    const sellerConsumablesTotal = recipe.selectedSellerConsumables.reduce((sum, consumableId) => {
      const consumable = sellerConsumables.find((c) => c.id === consumableId)
      return sum + (consumable ? consumable.pricePerUnit : 0)
    }, 0)

    const consumables = ffConsumablesTotal + sellerConsumablesTotal
    const total = servicesTotal + consumables

    return { services: servicesTotal, consumables, total }
  }

  // Получение рецептуры товара
  const getProductRecipe = (productId: string): ProductRecipe | undefined => {
    return productRecipes[productId]
  }

  // Проверка наличия выбранных компонентов для товара
  const hasSelectedComponents = (productId: string): boolean => {
    const recipe = productRecipes[productId]
    if (!recipe) return false

    return (
      recipe.selectedServices.length > 0 ||
      recipe.selectedFFConsumables.length > 0 ||
      recipe.selectedSellerConsumables.length > 0
    )
  }

  return {
    // Состояние рецептур
    productRecipes,
    setProductRecipes,

    // Данные компонентов
    fulfillmentServices,
    fulfillmentConsumables,
    sellerConsumables,

    // Функции управления рецептурами
    initializeProductRecipe,
    toggleService,
    toggleFFConsumable,
    toggleSellerConsumable,
    setWBCard,

    // Функции расчетов и получения данных
    calculateRecipeCost,
    getProductRecipe,
    hasSelectedComponents,
  }
}
