/**
 * ПРЯМОЕ СОЗДАНИЕ ПОСТАВОК WB - НОВАЯ МОДУЛЬНАЯ АРХИТЕКТУРА
 *
 * Рефакторинг direct-supply-creation.tsx
 * Композиция из блок-компонентов с использованием custom hooks
 */

'use client'

import { useQuery } from '@apollo/client'
import React, { useEffect, useCallback } from 'react'

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

// Блок-компоненты
import { ProductGridBlock } from './blocks/ProductGridBlock'
import { ProductSearchBlock } from './blocks/ProductSearchBlock'
import { ServicesConfigBlock } from './blocks/ServicesConfigBlock'
import { SupplierModalBlock } from './blocks/SupplierModalBlock'
import { SupplyItemsBlock } from './blocks/SupplyItemsBlock'
// Custom hooks
import { useFulfillmentServices } from './hooks/useFulfillmentServices'
import { useSupplierForm } from './hooks/useSupplierForm'
import { useSupplyCreation } from './hooks/useSupplyCreation'
import { useSupplyManagement } from './hooks/useSupplyManagement'
import { useWildberriesProducts } from './hooks/useWildberriesProducts'
// Типы
import type { DirectSupplyCreationProps } from './types/direct-supply.types'

export function DirectSupplyCreation({
  onComplete,
  onCreateSupply: _onCreateSupply,
  canCreateSupply: _canCreateSupply,
  isCreatingSupply: _isCreatingSupply,
  onCanCreateSupplyChange,
  selectedFulfillmentId,
  onServicesCostChange,
  onItemsPriceChange,
  onItemsCountChange,
  onConsumablesCostChange,
  onVolumeChange,
  onSuppliersChange,
}: DirectSupplyCreationProps) {
  // === ХУКИ ===

  // 1. Товары Wildberries
  const {
    searchTerm,
    setSearchTerm,
    loading: productsLoading,
    wbCards,
    loadCards: _loadCards,
    searchCards,
  } = useWildberriesProducts()

  // 2. Управление поставкой
  const {
    supplyItems,
    addToSupply,
    updateItemQuantity,
    updateItemPrice,
    removeItem,
    getTotalItemsCost,
    getTotalVolume,
    getTotalQuantity,
  } = useSupplyManagement()

  // 3. Услуги фулфилмента
  const {
    selectedServices,
    selectedConsumables,
    organizationServices,
    organizationSupplies,
    deliveryDateOriginal,
    selectedFulfillmentOrg,
    toggleService,
    toggleConsumable,
    setDeliveryDateOriginal,
    setSelectedFulfillmentOrg,
    loadOrganizationServices,
    loadOrganizationSupplies,
    getServicesCost,
    getConsumablesCost,
  } = useFulfillmentServices()

  // 4. Форма поставщиков
  const {
    suppliers,
    showSupplierModal,
    newSupplier,
    supplierErrors,
    setShowSupplierModal,
    updateSupplier,
    validateSupplier: _validateSupplier,
    resetSupplierForm: _resetSupplierForm,
    createSupplier,
  } = useSupplierForm()

  // 5. Создание поставки
  const {
    deliveryDate: _deliveryDate,
    selectedFulfillment: _selectedFulfillment,
    goodsQuantity: _goodsQuantity,
    goodsVolume: _goodsVolume,
    cargoPlaces: _cargoPlaces,
    goodsPrice: _goodsPrice,
    fulfillmentServicesPrice: _fulfillmentServicesPrice,
    logisticsPrice: _logisticsPrice,
    setDeliveryDate: _setDeliveryDate,
    setSelectedFulfillment: _setSelectedFulfillment,
    setGoodsQuantity: _setGoodsQuantity,
    setGoodsVolume: _setGoodsVolume,
    setCargoPlaces: _setCargoPlaces,
    setGoodsPrice: _setGoodsPrice,
    setFulfillmentServicesPrice: _setFulfillmentServicesPrice,
    setLogisticsPrice: _setLogisticsPrice,
    canCreateSupply: canCreateSupplyInternal,
    createSupply: _createSupplyInternal,
  } = useSupplyCreation({
    supplyItems,
    deliveryDateOriginal,
    selectedServices,
    selectedConsumables,
    selectedFulfillmentOrg,
    onComplete,
    getServicesCost: (quantity) => getServicesCost(quantity),
    getConsumablesCost: (quantity) => getConsumablesCost(quantity),
    getTotalItemsCost,
    getTotalQuantity,
  })

  // Загрузка контрагентов
  const { data: counterpartiesData } = useQuery(GET_MY_COUNTERPARTIES)

  // === ЭФФЕКТЫ ===

  // Загрузка услуг и расходников при выборе фулфилмента
  useEffect(() => {
    if (selectedFulfillmentId) {
      console.warn('Загружаем услуги и расходники для фулфилмента:', selectedFulfillmentId)
      loadOrganizationServices(selectedFulfillmentId)
      loadOrganizationSupplies(selectedFulfillmentId)
      setSelectedFulfillmentOrg(selectedFulfillmentId)
    }
  }, [selectedFulfillmentId, loadOrganizationServices, loadOrganizationSupplies, setSelectedFulfillmentOrg])

  // Уведомления о изменениях для родительского компонента
  useEffect(() => {
    if (onServicesCostChange) {
      const servicesCost = getServicesCost(getTotalQuantity())
      onServicesCostChange(servicesCost)
    }
  }, [selectedServices, selectedFulfillmentId, getTotalQuantity, onServicesCostChange, getServicesCost])

  useEffect(() => {
    if (onItemsPriceChange) {
      const totalItemsPrice = getTotalItemsCost()
      onItemsPriceChange(totalItemsPrice)
    }
  }, [supplyItems, onItemsPriceChange, getTotalItemsCost])

  useEffect(() => {
    if (onItemsCountChange) {
      onItemsCountChange(supplyItems.length > 0)
    }
  }, [supplyItems.length, onItemsCountChange])

  useEffect(() => {
    if (onConsumablesCostChange) {
      const consumablesCost = getConsumablesCost(getTotalQuantity())
      onConsumablesCostChange(consumablesCost)
    }
  }, [
    selectedConsumables,
    selectedFulfillmentId,
    supplyItems.length,
    onConsumablesCostChange,
    getConsumablesCost,
    getTotalQuantity,
  ])

  useEffect(() => {
    if (onVolumeChange) {
      const totalVolume = getTotalVolume()
      onVolumeChange(totalVolume)
    }
  }, [supplyItems, onVolumeChange, getTotalVolume])

  useEffect(() => {
    if (onCanCreateSupplyChange) {
      const canCreate = canCreateSupplyInternal()
      onCanCreateSupplyChange(canCreate)
    }
  }, [supplyItems, deliveryDateOriginal, selectedFulfillmentOrg, onCanCreateSupplyChange, canCreateSupplyInternal])

  useEffect(() => {
    if (onSuppliersChange) {
      const suppliersInfo = suppliers.map((supplier) => ({
        ...supplier,
        selected: supplyItems.some((item) => item.supplierId === supplier.id),
      }))
      onSuppliersChange(suppliersInfo)
    }
  }, [suppliers, supplyItems, onSuppliersChange])

  // === ОБРАБОТЧИКИ СОБЫТИЙ ===

  const handleAddToSupply = useCallback(
    (card: unknown, quantity: number, supplierId: string) => {
      addToSupply(card, quantity, supplierId)
    },
    [addToSupply],
  )

  const handleSupplierChange = useCallback(
    (field: keyof typeof newSupplier, value: string) => {
      updateSupplier(field, value)
    },
    [updateSupplier],
  )

  const handleCreateSupplier = useCallback(async () => {
    await createSupplier()
  }, [createSupplier])

  const handleServiceToggle = useCallback(
    (serviceId: string) => {
      toggleService(serviceId)
    },
    [toggleService],
  )

  const handleConsumableToggle = useCallback(
    (consumableId: string) => {
      toggleConsumable(consumableId)
    },
    [toggleConsumable],
  )

  const handleFulfillmentChange = useCallback(
    (fulfillmentId: string) => {
      setSelectedFulfillmentOrg(fulfillmentId)
      loadOrganizationServices(fulfillmentId)
      loadOrganizationSupplies(fulfillmentId)
    },
    [setSelectedFulfillmentOrg, loadOrganizationServices, loadOrganizationSupplies],
  )

  // === РЕНДЕР ===

  return (
    <div className="flex flex-col h-full space-y-4 w-full min-h-0">
      {/* БЛОК 1: ПОИСК ТОВАРОВ */}
      <ProductSearchBlock
        searchTerm={searchTerm}
        loading={productsLoading}
        onSearchChange={setSearchTerm}
        onSearch={searchCards}
      />

      {/* БЛОК 2: СЕТКА ТОВАРОВ */}
      <ProductGridBlock wbCards={wbCards} loading={productsLoading} onAddToSupply={handleAddToSupply} />

      {/* БЛОК 3: НАСТРОЙКИ ПОСТАВКИ */}
      <ServicesConfigBlock
        selectedFulfillmentId={selectedFulfillmentId}
        selectedServices={selectedServices}
        selectedConsumables={selectedConsumables}
        organizationServices={organizationServices}
        organizationSupplies={organizationSupplies}
        deliveryDateOriginal={deliveryDateOriginal}
        selectedFulfillmentOrg={selectedFulfillmentOrg}
        counterpartiesData={counterpartiesData}
        onServiceToggle={handleServiceToggle}
        onConsumableToggle={handleConsumableToggle}
        onDeliveryDateChange={setDeliveryDateOriginal}
        onFulfillmentChange={handleFulfillmentChange}
      />

      {/* БЛОК 4: ТОВАРЫ В ПОСТАВКЕ */}
      <SupplyItemsBlock
        supplyItems={supplyItems}
        onUpdateQuantity={updateItemQuantity}
        onUpdatePrice={updateItemPrice}
        onRemoveItem={removeItem}
      />

      {/* МОДАЛЬНОЕ ОКНО ПОСТАВЩИКА */}
      <SupplierModalBlock
        showSupplierModal={showSupplierModal}
        newSupplier={newSupplier}
        supplierErrors={supplierErrors}
        creatingSupplier={false} // TODO: подключить loading из хука
        onClose={() => setShowSupplierModal(false)}
        onSupplierChange={handleSupplierChange}
        onCreateSupplier={handleCreateSupplier}
      />
    </div>
  )
}
