/**
 * ХУКА ДЛЯ СОЗДАНИЯ ПОСТАВКИ
 *
 * Выделена из direct-supply-creation.tsx
 * Управляет настройками поставки и процессом создания
 */

import { useMutation } from '@apollo/client'
import { format } from 'date-fns'
import { ru } from 'date-fns/locale'
import { useState, useCallback } from 'react'
import { toast } from 'sonner'

import { CREATE_WILDBERRIES_SUPPLY } from '@/graphql/mutations'

import type {
  UseSupplyCreationReturn,
  SupplyItem,
  SupplyValidation,
  CostBreakdown,
  CreateSupplyVariables,
} from '../types/direct-supply.types'

interface UseSupplyCreationProps {
  supplyItems: SupplyItem[]
  deliveryDateOriginal: Date | undefined
  selectedServices: string[]
  selectedConsumables: string[]
  selectedFulfillmentOrg: string
  onComplete: () => void
  getServicesCost: (quantity: number) => number
  getConsumablesCost: (quantity: number) => number
  getTotalItemsCost: () => number
  getTotalQuantity: () => number
}

export function useSupplyCreation({
  supplyItems,
  deliveryDateOriginal,
  selectedServices,
  selectedConsumables,
  selectedFulfillmentOrg,
  onComplete,
  getServicesCost,
  getConsumablesCost,
  getTotalItemsCost,
  getTotalQuantity,
}: UseSupplyCreationProps): UseSupplyCreationReturn {
  // Состояния новой системы данных поставки
  const [deliveryDate, setDeliveryDate] = useState<string>('')
  const [selectedFulfillment, setSelectedFulfillment] = useState<string>('')
  const [goodsQuantity, setGoodsQuantity] = useState<number>(1200)
  const [goodsVolume, setGoodsVolume] = useState<number>(0)
  const [cargoPlaces, setCargoPlaces] = useState<number>(0)
  const [goodsPrice, setGoodsPrice] = useState<number>(0)
  const [fulfillmentServicesPrice, setFulfillmentServicesPrice] = useState<number>(0)
  const [logisticsPrice, setLogisticsPrice] = useState<number>(0)

  // Мутация создания поставки
  const [createSupply] = useMutation(CREATE_WILDBERRIES_SUPPLY, {
    onCompleted: (data) => {
      if (data.createWildberriesSupply.success) {
        toast.success(data.createWildberriesSupply.message)
        onComplete()
      } else {
        toast.error(data.createWildberriesSupply.message)
      }
    },
    onError: (error) => {
      toast.error('Ошибка при создании поставки')
      console.error('Error creating supply:', error)
    },
  })

  // Расчет общей суммы (не используется)
  const _getTotalSum = useCallback((): number => {
    return goodsPrice + fulfillmentServicesPrice + logisticsPrice
  }, [goodsPrice, fulfillmentServicesPrice, logisticsPrice])

  // Валидация возможности создания поставки
  const canCreateSupply = useCallback((): boolean => {
    return (
      supplyItems.length > 0 &&
      deliveryDateOriginal !== null &&
      selectedFulfillmentOrg !== '' &&
      supplyItems.every((item) => item.quantity > 0 && item.pricePerUnit > 0)
    )
  }, [supplyItems, deliveryDateOriginal, selectedFulfillmentOrg])

  // Детальная валидация
  const getSupplyValidation = useCallback((): SupplyValidation => {
    const errors: string[] = []

    if (supplyItems.length === 0) {
      errors.push('Добавьте товары в поставку')
    }

    if (!deliveryDateOriginal) {
      errors.push('Выберите дату поставки')
    }

    if (!selectedFulfillmentOrg) {
      errors.push('Выберите фулфилмент центр')
    }

    if (selectedServices.length === 0) {
      errors.push('Выберите минимум одну услугу')
    }

    const hasInvalidItems = supplyItems.some((item) => item.quantity <= 0 || item.pricePerUnit <= 0)
    if (hasInvalidItems) {
      errors.push('Все товары должны иметь количество > 0 и цену > 0')
    }

    return {
      hasItems: supplyItems.length > 0,
      hasServices: selectedServices.length > 0,
      hasDeliveryDate: !!deliveryDateOriginal,
      hasFulfillment: !!selectedFulfillmentOrg,
      isValid: errors.length === 0,
      errors,
    }
  }, [supplyItems, deliveryDateOriginal, selectedFulfillmentOrg, selectedServices])

  // Разбивка стоимости (не используется)
  const _getCostBreakdown = useCallback((): CostBreakdown => {
    const itemsCost = getTotalItemsCost()
    const servicesCost = getServicesCost(getTotalQuantity())
    const consumablesCost = getConsumablesCost(getTotalQuantity())
    const logisticsCost = logisticsPrice

    return {
      itemsCost,
      servicesCost,
      consumablesCost,
      logisticsCost,
      totalCost: itemsCost + servicesCost + consumablesCost + logisticsCost,
    }
  }, [getTotalItemsCost, getServicesCost, getConsumablesCost, getTotalQuantity, logisticsPrice])

  // Создание поставки
  const createSupplyInternal = useCallback(async () => {
    const validation = getSupplyValidation()

    if (!validation.isValid) {
      validation.errors.forEach((error) => toast.error(error))
      return
    }

    if (!deliveryDateOriginal) {
      toast.error('Выберите дату поставки')
      return
    }

    try {
      const variables: CreateSupplyVariables = {
        fulfillmentCenterId: selectedFulfillmentOrg,
        deliveryDate: format(deliveryDateOriginal, 'yyyy-MM-dd', { locale: ru }),
        items: supplyItems.map((item) => ({
          cardId: item.card.nmID.toString(),
          quantity: item.quantity,
          price: item.pricePerUnit,
        })),
        services: selectedServices,
        consumables: selectedConsumables,
      }

      await createSupply({ variables })
    } catch (error) {
      console.error('Ошибка создания поставки:', error)
    }
  }, [
    getSupplyValidation,
    deliveryDateOriginal,
    selectedFulfillmentOrg,
    supplyItems,
    selectedServices,
    selectedConsumables,
    createSupply,
  ])

  return {
    // Состояния новой системы
    deliveryDate,
    selectedFulfillment,
    goodsQuantity,
    goodsVolume,
    cargoPlaces,
    goodsPrice,
    fulfillmentServicesPrice,
    logisticsPrice,

    // Функции управления состоянием
    setDeliveryDate,
    setSelectedFulfillment,
    setGoodsQuantity,
    setGoodsVolume,
    setCargoPlaces,
    setGoodsPrice,
    setFulfillmentServicesPrice,
    setLogisticsPrice,

    // Функции валидации и создания
    canCreateSupply,
    createSupply: createSupplyInternal,
  }
}
