/**
 * ХУКА ДЛЯ ЛОГИКИ КАТАЛОГА ТОВАРОВ
 *
 * Выделена из create-suppliers-supply-page.tsx
 * Управляет загрузкой и фильтрацией товаров поставщика
 */

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

import { GET_ORGANIZATION_PRODUCTS } from '@/graphql/queries'

import type { GoodsSupplier, GoodsProduct } from '../types/supply-creation.types'

interface UseProductCatalogProps {
  selectedSupplier: GoodsSupplier | null
}

export function useProductCatalog({ selectedSupplier }: UseProductCatalogProps) {
  // Состояния
  const [productSearchQuery] = useState('')
  const [allSelectedProducts, setAllSelectedProducts] = useState<Array<GoodsProduct & { selectedQuantity: number }>>([])
  const [productQuantities, setProductQuantities] = useState<Record<string, number>>({})

  // Загружаем каталог товаров согласно rules2.md 13.3
  const {
    data: productsData,
    loading: productsLoading,
    error: productsError,
  } = useQuery(GET_ORGANIZATION_PRODUCTS, {
    variables: {
      organizationId: selectedSupplier?.id || '',
      search: productSearchQuery,
      category: '',
      type: 'PRODUCT', // КРИТИЧЕСКИ ВАЖНО: показываем только PRODUCT, не CONSUMABLE
    },
    skip: !selectedSupplier || !selectedSupplier.id,
    fetchPolicy: 'network-only',
    errorPolicy: 'all',
    onError: (error) => {
      try {
        console.warn('🚨 GET_ORGANIZATION_PRODUCTS ERROR:', {
          errorMessage: error?.message || 'Unknown error',
          hasGraphQLErrors: !!error?.graphQLErrors?.length,
          hasNetworkError: !!error?.networkError,
          variables: {
            organizationId: selectedSupplier?.id || 'not_selected',
            search: productSearchQuery || 'empty',
            category: '',
            type: 'PRODUCT',
          },
          selectedSupplier: selectedSupplier
            ? {
                id: selectedSupplier.id,
                name: selectedSupplier.name || selectedSupplier.fullName || 'Unknown',
              }
            : 'not_selected',
        })
      } catch (logError) {
        console.warn('❌ Error in error handler:', logError)
      }
    },
  })

  // Получаем товары выбранного поставщика
  const products = useMemo(() => {
    return (productsData?.organizationProducts || []).filter((product: GoodsProduct) => {
      try {
        return product && product.id && product.name
      } catch (error) {
        console.warn('❌ Error filtering product:', error)
        return false
      }
    })
  }, [productsData])

  // Функции для работы с количествами товаров
  const getProductQuantity = (productId: string): number => {
    return productQuantities[productId] || 0
  }

  const setProductQuantity = (productId: string, quantity: number): void => {
    setProductQuantities((prev) => ({
      ...prev,
      [productId]: Math.max(0, quantity),
    }))
  }

  // Добавление товара в выбранные с количеством
  const addProductToSelected = (product: GoodsProduct, quantity: number = 0) => {
    const productWithQuantity = {
      ...product,
      selectedQuantity: quantity,
    }

    setAllSelectedProducts((prev) => {
      const existingIndex = prev.findIndex((p) => p.id === product.id)
      if (existingIndex >= 0) {
        // Обновляем количество существующего товара
        const updated = [...prev]
        updated[existingIndex] = { ...updated[existingIndex], selectedQuantity: quantity }
        return updated
      } else {
        // Добавляем новый товар
        return [...prev, productWithQuantity]
      }
    })

    // Синхронизируем с productQuantities
    setProductQuantity(product.id, quantity)
  }

  // Удаление товара из выбранных
  const removeProductFromSelected = (productId: string) => {
    setAllSelectedProducts((prev) => prev.filter((p) => p.id !== productId))
    setProductQuantities((prev) => {
      const updated = { ...prev }
      delete updated[productId]
      return updated
    })
  }

  // Обновление количества выбранного товара
  const updateSelectedProductQuantity = (productId: string, quantity: number) => {
    if (quantity <= 0) {
      removeProductFromSelected(productId)
      return
    }

    setAllSelectedProducts((prev) => prev.map((p) => (p.id === productId ? { ...p, selectedQuantity: quantity } : p)))
    setProductQuantity(productId, quantity)
  }

  return {
    // Состояние товаров
    products,
    allSelectedProducts,
    setAllSelectedProducts,
    productQuantities,
    setProductQuantities,

    // Статусы загрузки
    loading: productsLoading,
    error: productsError,

    // Функции управления товарами
    getProductQuantity,
    setProductQuantity,
    addProductToSelected,
    removeProductFromSelected,
    updateSelectedProductQuantity,
  }
}
