// =============================================================================
// 🚀 ХУК ДЛЯ СОЗДАНИЯ ПОСТАВКИ
// =============================================================================

import { useMutation } from '@apollo/client'
import { useRouter } from 'next/navigation'
import { useState, useCallback } from 'react'
import { toast } from 'sonner'

import {
  CREATE_FULFILLMENT_CONSUMABLE_SUPPLY,
  GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES,
} from '@/graphql/queries/fulfillment-consumables-v2'

import type { 
  FulfillmentConsumableSupplier,
  SelectedFulfillmentConsumable,
  SupplyCreationInput,
  CreateSupplyMutationResponse,
  UseSupplyCreationReturn, 
} from '../types'

interface UseSupplyCreationProps {
  selectedSupplier: FulfillmentConsumableSupplier | null
  selectedConsumables: SelectedFulfillmentConsumable[]
  selectedLogistics: any | null  // Добавляем логистику
  deliveryDate: string
  notes: string
  resetForm: () => void
}

export function useSupplyCreation({
  selectedSupplier,
  selectedConsumables,
  selectedLogistics,
  deliveryDate,
  notes,
  resetForm,
}: UseSupplyCreationProps): UseSupplyCreationReturn {
  const router = useRouter()
  const [isCreating, setIsCreating] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Мутация для создания заказа поставки расходников v2
  const [createSupplyMutation] = useMutation<CreateSupplyMutationResponse>(CREATE_FULFILLMENT_CONSUMABLE_SUPPLY)

  // Функция создания поставки
  const createSupply = useCallback(async () => {
    // Валидация обязательных полей
    if (!selectedSupplier || selectedConsumables.length === 0 || !deliveryDate) {
      const errorMessage = 'Заполните все обязательные поля: поставщик, расходники и дата доставки'
      setError(errorMessage)
      toast.error(errorMessage)
      return
    }

    setIsCreating(true)
    setError(null)

    try {
      // Формируем input для системы v2
      const input: SupplyCreationInput = {
        supplierId: selectedSupplier.id,
        logisticsPartnerId: selectedLogistics?.id || undefined,  // Добавляем логистику
        requestedDeliveryDate: deliveryDate,
        items: selectedConsumables.map((consumable) => ({
          productId: consumable.id,
          requestedQuantity: consumable.selectedQuantity,
        })),
        notes: notes || undefined,
      }

      console.warn('🚀 СОЗДАНИЕ ПОСТАВКИ v2 - INPUT:', input)

      const result = await createSupplyMutation({
        variables: { input },
        refetchQueries: [
          { query: GET_MY_FULFILLMENT_CONSUMABLE_SUPPLIES }, // Обновляем новый v2 запрос
        ],
      })

      console.warn('🎯 РЕЗУЛЬТАТ СОЗДАНИЯ ПОСТАВКИ v2:', result)

      if (result.data?.createFulfillmentConsumableSupply?.success) {
        toast.success('Поставка расходников создана успешно!')
        
        // Очищаем форму
        resetForm()

        // Перенаправляем на страницу детальных поставок
        router.push('/fulfillment-supplies/detailed-supplies')
      } else {
        const errorMessage = result.data?.createFulfillmentConsumableSupply?.message || 'Ошибка при создании поставки'
        setError(errorMessage)
        toast.error(errorMessage)
      }
    } catch (error) {
      const errorMessage = 'Ошибка при создании поставки расходников'
      console.error('Error creating fulfillment consumables supply v2:', error)
      setError(errorMessage)
      toast.error(errorMessage)
    } finally {
      setIsCreating(false)
    }
  }, [selectedSupplier, selectedConsumables, selectedLogistics, deliveryDate, notes, resetForm, router, createSupplyMutation])

  return {
    createSupply,
    isCreating,
    error,
  }
}