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

'use client'

import { ArrowLeft } from 'lucide-react'
import { useRouter } from 'next/navigation'
import React, { useCallback, useState, useEffect } from 'react'

import { Sidebar } from '@/components/dashboard/sidebar'
import { Button } from '@/components/ui/button'
import { useAuthContext } from '@/contexts/AuthContext'
import { useSidebar } from '@/hooks/useSidebar'

import { CartBlock } from './blocks/CartBlock'
import { DetailedCatalogBlock } from './blocks/DetailedCatalogBlock'
import { ProductCardsBlock } from './blocks/ProductCardsBlock'
import { SuppliersBlock } from './blocks/SuppliersBlock'
import { useProductCatalog } from './hooks/useProductCatalog'
import { useRecipeBuilder } from './hooks/useRecipeBuilder'
import { useSupplierSelection } from './hooks/useSupplierSelection'
import { useSupplyCart } from './hooks/useSupplyCart'
import type { GoodsSupplier, GoodsProduct, ProductRecipe } from './types/supply-creation.types'

export function CreateSuppliersSupplyPage() {
  const router = useRouter()
  const { user: _user } = useAuthContext()
  const { getSidebarMargin } = useSidebar()

  // 1. ХУКА ВЫБОРА ПОСТАВЩИКОВ
  const {
    selectedSupplier,
    setSelectedSupplier,
    searchQuery,
    setSearchQuery,
    suppliers,
    allCounterparties,
    loading: suppliersLoading,
    error: suppliersError,
  } = useSupplierSelection()

  // 2. ХУКА КАТАЛОГА ТОВАРОВ
  const {
    products,
    allSelectedProducts,
    setAllSelectedProducts,
    productQuantities: _productQuantities,
    loading: _productsLoading,
    getProductQuantity,
    addProductToSelected,
    updateSelectedProductQuantity,
    removeProductFromSelected,
  } = useProductCatalog({ selectedSupplier })

  // 3. ХУКА ПОСТРОЕНИЯ РЕЦЕПТУР (инициализируем с пустым selectedFulfillment)
  const [tempSelectedFulfillment, setTempSelectedFulfillment] = useState('')
  
  const {
    productRecipes,
    setProductRecipes,
    fulfillmentServices,
    fulfillmentConsumables,
    sellerConsumables,
    initializeProductRecipe,
    getProductRecipe: _getProductRecipe,
  } = useRecipeBuilder({ selectedFulfillment: tempSelectedFulfillment })

  // 4. ХУКА КОРЗИНЫ ПОСТАВОК (теперь с актуальными рецептами)
  const {
    selectedGoods,
    setSelectedGoods,
    deliveryDate,
    setDeliveryDate,
    selectedLogistics,
    setSelectedLogistics,
    selectedFulfillment,
    setSelectedFulfillment: setSelectedFulfillmentOriginal,
    isCreatingSupply,
    totalGoodsAmount,
    isFormValid,
    addToCart,
    removeFromCart,
    handleCreateSupply,
  } = useSupplyCart({
    selectedSupplier,
    allCounterparties,
    productRecipes: productRecipes,
  })
  
  // Синхронизируем selectedFulfillment между хуками
  useEffect(() => {
    setTempSelectedFulfillment(selectedFulfillment)
  }, [selectedFulfillment])
  
  const setSelectedFulfillment = useCallback((fulfillment: string) => {
    setSelectedFulfillmentOriginal(fulfillment)
  }, [setSelectedFulfillmentOriginal])

  // Обработчики событий для блоков
  const handleSupplierSelect = useCallback(
    (supplier: GoodsSupplier) => {
      // Сбрасываем выбранные товары только при смене поставщика
      if (selectedSupplier?.id !== supplier.id) {
        setAllSelectedProducts([])
        setSelectedGoods([])
      }
      setSelectedSupplier(supplier)
    },
    [selectedSupplier, setSelectedSupplier, setAllSelectedProducts, setSelectedGoods],
  )

  const handleProductAdd = useCallback(
    (product: GoodsProduct) => {
      const quantity = getProductQuantity(product.id) || 0
      addProductToSelected(product, quantity)
      initializeProductRecipe(product.id)

      // Добавляем в корзину только если количество больше 0
      if (quantity > 0) {
        addToCart(product, quantity)
      }
    },
    [getProductQuantity, addProductToSelected, initializeProductRecipe, addToCart],
  )

  const handleQuantityChange = useCallback(
    (productId: string, quantity: number) => {
      updateSelectedProductQuantity(productId, quantity)

      // Синхронизируем с корзиной
      const product = allSelectedProducts.find((p) => p.id === productId)
      if (product && quantity > 0) {
        addToCart(product, quantity)
      } else if (quantity === 0) {
        removeFromCart(productId)
        // НЕ удаляем товар из блока 3, только из корзины
      }
    },
    [updateSelectedProductQuantity, allSelectedProducts, addToCart, removeFromCart],
  )

  const handleRecipeChange = useCallback(
    (productId: string, recipe: ProductRecipe) => {
      console.log('📝 handleRecipeChange вызван:', {
        productId: productId,
        recipe: recipe,
      })
      
      setProductRecipes((prev) => ({
        ...prev,
        [productId]: recipe,
      }))
    },
    [setProductRecipes],
  )

  // Обработчик ошибок
  if (suppliersError) {
    return (
      <div className="h-screen flex overflow-hidden">
        <Sidebar />
        <main className={`flex-1 ${getSidebarMargin()} overflow-hidden transition-all duration-300`}>
          <div className="h-full flex items-center justify-center">
            <div className="text-center">
              <div className="text-red-400 text-lg font-semibold mb-2">Ошибка загрузки данных</div>
              <div className="text-white/60 text-sm mb-4">Не удалось загрузить список поставщиков</div>
              <Button onClick={() => router.push('/supplies')} variant="outline" className="text-white border-white/20">
                Вернуться к поставкам
              </Button>
            </div>
          </div>
        </main>
      </div>
    )
  }

  return (
    <div className="h-screen flex overflow-hidden">
      <Sidebar />
      <main className={`flex-1 ${getSidebarMargin()} overflow-hidden transition-all duration-300`}>
        <div className="h-full flex gap-2 pt-4 pb-4">
          {/* ЛЕВАЯ ЧАСТЬ - ЗАГОЛОВОК И БЛОКИ 1-3 */}
          <div className="flex-1 flex flex-col">
            {/* ЗАГОЛОВОК И НАВИГАЦИЯ */}
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl p-4 mb-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Button
                    onClick={() => router.push('/supplies')}
                    variant="ghost"
                    size="sm"
                    className="text-white/70 hover:text-white hover:bg-white/10"
                  >
                    <ArrowLeft className="h-4 w-4 mr-2" />
                    Назад к поставкам
                  </Button>
                  <div className="h-4 w-px bg-white/20"></div>
                  <h1 className="text-white font-semibold text-lg">Создание поставки от поставщика</h1>
                </div>
                {selectedSupplier && (
                  <div className="text-white/60 text-sm">
                    Поставщик: {selectedSupplier.name || selectedSupplier.fullName}
                  </div>
                )}
              </div>
            </div>

            {/* БЛОКИ 1-3 */}
            <div className="flex-1 flex flex-col gap-2 min-h-0">
              {/* БЛОК 1: ВЫБОР ПОСТАВЩИКОВ - Минималистичная высота */}
              <div className="h-32">
                {/* МИНИМАЛИЗМ: убрали поиск, уменьшили с h-48 до h-32 */}
                <SuppliersBlock
                  suppliers={suppliers}
                  selectedSupplier={selectedSupplier}
                  searchQuery={searchQuery}
                  loading={suppliersLoading}
                  onSupplierSelect={handleSupplierSelect}
                  onSearchChange={setSearchQuery}
                />
              </div>

              {/* БЛОК 2: КАРТОЧКИ ТОВАРОВ (МИНИ-ПРЕВЬЮ) - Оптимальная высота h-[196px] */}
              <div className="h-[196px]">
                {/* ОТКАТ: было flex-shrink-0, вернули h-72 */}
                <ProductCardsBlock
                  products={products}
                  selectedSupplier={selectedSupplier}
                  selectedProducts={allSelectedProducts}
                  onProductAdd={handleProductAdd}
                />
              </div>

              {/* БЛОК 3: ДЕТАЛЬНЫЙ КАТАЛОГ С РЕЦЕПТУРОЙ - До низа сайдбара */}
              <div className="flex-1 min-h-0">
                <DetailedCatalogBlock
                  allSelectedProducts={allSelectedProducts}
                  productRecipes={productRecipes}
                  fulfillmentServices={fulfillmentServices}
                  fulfillmentConsumables={fulfillmentConsumables}
                  sellerConsumables={sellerConsumables}
                  deliveryDate={deliveryDate}
                  selectedFulfillment={selectedFulfillment}
                  allCounterparties={allCounterparties}
                  onQuantityChange={handleQuantityChange}
                  onRecipeChange={handleRecipeChange}
                  onDeliveryDateChange={setDeliveryDate}
                  onFulfillmentChange={setSelectedFulfillment}
                  onProductRemove={(productId) => {
                    removeFromCart(productId)
                    removeProductFromSelected(productId)
                  }}
                />
              </div>
            </div>
          </div>

          {/* ПРАВАЯ КОЛОНКА - БЛОК 4: КОРЗИНА */}
            <CartBlock
              selectedGoods={selectedGoods}
              selectedSupplier={selectedSupplier}
              deliveryDate={deliveryDate}
              selectedFulfillment={selectedFulfillment}
              selectedLogistics={selectedLogistics}
              allCounterparties={allCounterparties}
              totalAmount={totalGoodsAmount}
              isFormValid={isFormValid}
              isCreatingSupply={isCreatingSupply}
              // Данные для расчета с рецептурой
              allSelectedProducts={allSelectedProducts}
              productRecipes={productRecipes}
              fulfillmentServices={fulfillmentServices}
              fulfillmentConsumables={fulfillmentConsumables}
              sellerConsumables={sellerConsumables}
              onLogisticsChange={setSelectedLogistics}
              onCreateSupply={handleCreateSupply}
              onItemRemove={removeFromCart}
            />
        </div>
      </main>
    </div>
  )
}
