// =============================================================================
// 📊 ХУК ДЛЯ УПРАВЛЕНИЯ КОЛИЧЕСТВОМ ТОВАРОВ
// =============================================================================

import { useCallback } from 'react'
import { toast } from 'sonner'

import type { 
  FulfillmentConsumableSupplier,
  FulfillmentConsumableProduct,
  SelectedFulfillmentConsumable,
  UseQuantityManagementReturn, 
} from '../types'

interface UseQuantityManagementProps {
  selectedSupplier: FulfillmentConsumableSupplier | null
  selectedConsumables: SelectedFulfillmentConsumable[]
  products: FulfillmentConsumableProduct[]
  setSelectedConsumables: (updater: SelectedFulfillmentConsumable[] | ((prev: SelectedFulfillmentConsumable[]) => SelectedFulfillmentConsumable[])) => void
}

export function useQuantityManagement({
  selectedSupplier,
  selectedConsumables,
  products,
  setSelectedConsumables,
}: UseQuantityManagementProps): UseQuantityManagementReturn {
  
  // Обновление количества выбранного расходника
  const updateConsumableQuantity = useCallback((productId: string, quantity: number) => {
    const product = products.find((p: FulfillmentConsumableProduct) => p.id === productId)
    if (!product || !selectedSupplier) return

    // 🔒 ВАЛИДАЦИЯ ОСТАТКОВ согласно бизнес-правилам (раздел 6.2)
    if (quantity > 0) {
      const availableStock = (product.stock || product.quantity || 0) - (product.ordered || 0)

      if (quantity > availableStock) {
        toast.error(`❌ Недостаточно остатков!\nДоступно: ${availableStock} шт.\nЗапрашивается: ${quantity} шт.`)
        return
      }
    }

    setSelectedConsumables((prev: SelectedFulfillmentConsumable[]) => {
      const existing = prev.find((p: SelectedFulfillmentConsumable) => p.id === productId)

      if (quantity === 0) {
        // Удаляем расходник если количество 0
        return prev.filter((p: SelectedFulfillmentConsumable) => p.id !== productId)
      }

      if (existing) {
        // Обновляем количество существующего расходника
        return prev.map((p: SelectedFulfillmentConsumable) => (p.id === productId ? { ...p, selectedQuantity: quantity } : p))
      } else {
        // Добавляем новый расходник
        return [
          ...prev,
          {
            id: product.id,
            name: product.name,
            price: product.price,
            selectedQuantity: quantity,
            unit: product.unit || 'шт',
            category: product.category?.name || 'Расходники',
            supplierId: selectedSupplier.id,
            supplierName: selectedSupplier.name || selectedSupplier.fullName || 'Поставщик',
          },
        ]
      }
    })
  }, [products, selectedSupplier, setSelectedConsumables])

  // Получение выбранного количества для товара
  const getSelectedQuantity = useCallback((productId: string): number => {
    const selected = selectedConsumables.find((p) => p.id === productId)
    return selected ? selected.selectedQuantity : 0
  }, [selectedConsumables])

  // Расчет общей стоимости
  const getTotalAmount = useCallback(() => {
    return selectedConsumables.reduce((sum, consumable) => sum + consumable.price * consumable.selectedQuantity, 0)
  }, [selectedConsumables])

  // Расчет общего количества товаров
  const getTotalItems = useCallback(() => {
    return selectedConsumables.reduce((sum, consumable) => sum + consumable.selectedQuantity, 0)
  }, [selectedConsumables])

  return {
    updateConsumableQuantity,
    getSelectedQuantity,
    getTotalAmount,
    getTotalItems,
  }
}