// =============================================================================
// 🧩 МОДУЛЬНАЯ ВЕРСИЯ - СОЗДАНИЕ ПОСТАВОК РАСХОДНИКОВ ФУЛФИЛМЕНТА V2
// =============================================================================
// ВНИМАНИЕ: Визуал остается ТОЧНО таким же как в монолитной версии!
// Рефакторинг касается только архитектуры - разделение на модули

'use client'

import { useRouter } from 'next/navigation'
import React from 'react'

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

// 📦 Импорт модульных компонентов
import { PageHeader, SuppliersBlock, ConsumablesBlock, ShoppingCartBlock } from './blocks'
// 🔧 Импорт бизнес-хуков
import {
  useSupplierData,
  useProductData,
  useSupplyForm,
  useQuantityManagement,
  useSupplyCreation,
  useCurrencyFormatting,
} from './hooks'

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

  // 📋 Управление состоянием формы
  const {
    selectedSupplier,
    selectedLogistics,
    selectedConsumables,
    searchQuery,
    productSearchQuery,
    deliveryDate,
    notes,
    setSelectedSupplier,
    setSelectedLogistics,
    setSelectedConsumables,
    setSearchQuery,
    setProductSearchQuery,
    setDeliveryDate,
    setNotes,
    resetForm,
  } = useSupplyForm()

  // 🏢 Данные поставщиков
  const {
    suppliers,
    logisticsPartners,
    filteredSuppliers,
    loading: suppliersLoading,
  } = useSupplierData({ searchQuery })

  // 📦 Данные товаров
  const { products, loading: productsLoading } = useProductData({
    selectedSupplier,
    productSearchQuery,
  })

  // 📊 Управление количеством
  const { updateConsumableQuantity, getSelectedQuantity, getTotalAmount, getTotalItems } = useQuantityManagement({
    selectedSupplier,
    selectedConsumables,
    products,
    setSelectedConsumables,
  })

  // 🚀 Создание поставки
  const { createSupply, isCreating: isCreatingSupply } = useSupplyCreation({
    selectedSupplier,
    selectedConsumables,
    selectedLogistics,
    deliveryDate,
    notes,
    resetForm,
  })

  // 💰 Форматирование валюты
  const { formatCurrency } = useCurrencyFormatting()

  // 🔄 Обработчики событий
  const handleBack = () => {
    // Вариант 1: Новый URL (активный)
    router.push('/fulfillment/supplies/detailed-supplies')
    // Вариант 2: Старый URL (для отката)
    // router.push('/fulfillment-supplies/detailed-supplies')
  }

  return (
    <div className="h-screen flex overflow-hidden">
      <Sidebar />
      <main className={`flex-1 ${getSidebarMargin()} overflow-auto transition-all duration-300`}>
        <div className="min-h-full w-full flex flex-col px-3 py-2">
          {/* 📄 Заголовок страницы */}
          <PageHeader onBack={handleBack} />

          {/* 🧩 Основной контент с двумя блоками */}
          <div className="flex-1 flex gap-3 min-h-0">
            {/* 📦 Левая колонка - Поставщики и Расходники */}
            <div className="flex-1 flex flex-col gap-3 min-h-0">
              {/* 🏢 Блок поставщиков */}
              <SuppliersBlock
                suppliers={suppliers}
                filteredSuppliers={filteredSuppliers}
                selectedSupplier={selectedSupplier}
                searchQuery={searchQuery}
                loading={suppliersLoading}
                onSelectSupplier={setSelectedSupplier}
                onSearchChange={setSearchQuery}
              />

              {/* 📦 Блок расходников */}
              <ConsumablesBlock
                selectedSupplier={selectedSupplier}
                products={products}
                productsLoading={productsLoading}
                productSearchQuery={productSearchQuery}
                getSelectedQuantity={getSelectedQuantity}
                onProductSearchChange={setProductSearchQuery}
                onUpdateQuantity={updateConsumableQuantity}
                formatCurrency={formatCurrency}
              />
            </div>

            {/* 🛒 Правая колонка - Корзина */}
            <div className="w-72 flex-shrink-0">
              <ShoppingCartBlock
                selectedConsumables={selectedConsumables}
                deliveryDate={deliveryDate}
                notes={notes}
                selectedLogistics={selectedLogistics}
                logisticsPartners={logisticsPartners}
                isCreatingSupply={isCreatingSupply}
                getTotalAmount={getTotalAmount}
                getTotalItems={getTotalItems}
                formatCurrency={formatCurrency}
                onUpdateQuantity={updateConsumableQuantity}
                onSetDeliveryDate={setDeliveryDate}
                onSetNotes={setNotes}
                onSetLogistics={setSelectedLogistics}
                onCreateSupply={createSupply}
              />
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
