'use client'

import React from 'react'

import { CancelConfirmDialog } from './blocks/CancelConfirmDialog'
import { ContextMenu } from './blocks/ContextMenu'
import { SupplyRowV2Block } from './blocks/SupplyRowV2Block'
import { Table, TableBody } from './blocks/TableComponents'
import { TableHeaderV2Block } from './blocks/TableHeaderV2Block'
import { useContextMenu } from './hooks/useContextMenu'
import { useExpansionState } from './hooks/useExpansionState'
import { useGoodsSuppliesV2, useGoodsSupplyV2Actions } from './hooks/useGoodsSuppliesV2'
import type { MultiLevelSuppliesTableV2Props, GoodsSupplyOrderV2 } from './types/v2-types'

// ========== МОДУЛЬНАЯ ВЕРСИЯ MULTILEVEL SUPPLIES TABLE V2 ==========
// Компонент многоуровневой таблицы товарных поставок V2
// Специализирован под новые V2 типы данных из GraphQL

// Hook для управления V2 инпутами (адаптированный)
function useInputManagementV2(
  supplies: GoodsSupplyOrderV2[],
  onVolumeChange?: (supplyId: string, volume: number | null) => void,
  onPackagesChange?: (supplyId: string, packagesCount: number | null) => void,
  _onUpdateComplete?: (supplyId: string, field: 'volume' | 'packages') => void,
) {
  // Локальное состояние для инпутов
  const [inputValues, setInputValues] = React.useState<{[key: string]: {volume: string, packages: string}}>({})
  const [pendingUpdates, setPendingUpdates] = React.useState<Set<string>>(new Set())

  // Синхронизация с V2 данными
  React.useEffect(() => {
    setInputValues(prev => {
      const newValues: {[key: string]: {volume: string, packages: string}} = {}
      supplies.forEach(supply => {
        const isVolumePending = pendingUpdates.has(`${supply.id}-volume`)
        const isPackagesPending = pendingUpdates.has(`${supply.id}-packages`)
        
        newValues[supply.id] = {
          volume: isVolumePending ? (prev[supply.id]?.volume ?? '') : (supply.estimatedVolume?.toString() ?? ''),
          packages: isPackagesPending ? (prev[supply.id]?.packages ?? '') : (supply.packagesCount?.toString() ?? ''),
        }
      })
      
      const hasChanges = supplies.some(supply => {
        const isVolumePending = pendingUpdates.has(`${supply.id}-volume`)
        const isPackagesPending = pendingUpdates.has(`${supply.id}-packages`)
        
        if (isVolumePending || isPackagesPending) return false
        
        const volumeChanged = prev[supply.id]?.volume !== (supply.estimatedVolume?.toString() ?? '')
        const packagesChanged = prev[supply.id]?.packages !== (supply.packagesCount?.toString() ?? '')
        
        return volumeChanged || packagesChanged
      })
      
      return hasChanges ? newValues : prev
    })
  }, [supplies, pendingUpdates])

  // Обработчики изменений
  const handleVolumeChange = React.useCallback((supplyId: string, value: string) => {
    setInputValues(prev => ({
      ...prev,
      [supplyId]: {
        ...prev[supplyId],
        volume: value,
      },
    }))
  }, [])

  const handlePackagesChange = React.useCallback((supplyId: string, value: string) => {
    setInputValues(prev => ({
      ...prev,
      [supplyId]: {
        ...prev[supplyId],
        packages: value,
      },
    }))
  }, [])

  const handleVolumeBlur = React.useCallback((supplyId: string) => {
    const value = inputValues[supplyId]?.volume
    if (!value || value.trim() === '') {
      onVolumeChange?.(supplyId, null)
      return
    }

    const numericValue = parseFloat(value)
    if (!isNaN(numericValue)) {
      setPendingUpdates(prev => new Set(prev).add(`${supplyId}-volume`))
      onVolumeChange?.(supplyId, numericValue)
      
      setTimeout(() => {
        setPendingUpdates(prev => {
          const newSet = new Set(prev)
          newSet.delete(`${supplyId}-volume`)
          return newSet
        })
        onUpdateComplete?.(supplyId, 'volume')
      }, 500)
    }
  }, [inputValues, onVolumeChange, onUpdateComplete])

  const handlePackagesBlur = React.useCallback((supplyId: string) => {
    const value = inputValues[supplyId]?.packages
    if (!value || value.trim() === '') {
      onPackagesChange?.(supplyId, null)
      return
    }

    const numericValue = parseInt(value, 10)
    if (!isNaN(numericValue)) {
      setPendingUpdates(prev => new Set(prev).add(`${supplyId}-packages`))
      onPackagesChange?.(supplyId, numericValue)
      
      setTimeout(() => {
        setPendingUpdates(prev => {
          const newSet = new Set(prev)
          newSet.delete(`${supplyId}-packages`)
          return newSet
        })
        onUpdateComplete?.(supplyId, 'packages')
      }, 500)
    }
  }, [inputValues, onPackagesChange, onUpdateComplete])

  return {
    inputValues,
    pendingUpdates,
    handleVolumeChange,
    handlePackagesChange,
    handleVolumeBlur,
    handlePackagesBlur,
  }
}

export function MultiLevelSuppliesTableV2({
  supplies: propSupplies,
  loading: propLoading,
  userRole = 'SELLER',
  activeTab,
  onSupplyAction: propOnSupplyAction,
  onVolumeChange,
  onPackagesChange,
  onUpdateComplete,
}: MultiLevelSuppliesTableV2Props) {
  // 🔄 SMART DATA SOURCE: Используем GraphQL данные если переданные props пусты
  const shouldUseGraphQL = !propSupplies || propSupplies.length === 0
  
  const graphqlData = useGoodsSuppliesV2(userRole)
  const graphqlActions = useGoodsSupplyV2Actions(userRole, graphqlData.refetch)
  
  // Выбираем источник данных
  const supplies = shouldUseGraphQL ? graphqlData.supplies : (propSupplies || [])
  const loading = shouldUseGraphQL ? graphqlData.loading : (propLoading || false)
  const error = shouldUseGraphQL ? graphqlData.error : null
  
  // Выбираем обработчик действий
  const onSupplyAction = propOnSupplyAction || graphqlActions.handleSupplyAction

  // Hooks для управления состоянием
  const expansionState = useExpansionState()
  const inputManagement = useInputManagementV2(supplies, onVolumeChange, onPackagesChange, onUpdateComplete)
  const contextMenu = useContextMenu(onSupplyAction)

  // Обработка ошибок GraphQL
  if (error) {
    console.error('❌ GraphQL ошибка V2 поставок:', error)
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-red-400 text-center">
          <div className="text-lg font-semibold">Ошибка загрузки V2 поставок</div>
          <div className="text-sm text-white/60 mt-2">{error.message}</div>
          <button 
            onClick={() => graphqlData.refetch()}
            className="mt-4 px-4 py-2 bg-red-500/20 border border-red-500/30 text-red-300 rounded hover:bg-red-500/30"
          >
            Попробовать еще раз
          </button>
        </div>
      </div>
    )
  }

  // Индикатор загрузки
  if (loading && supplies.length === 0) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-white/60">
          <div className="animate-spin inline-block w-6 h-6 border-2 border-white/30 border-t-white/60 rounded-full mr-3"></div>
          Загрузка V2 товарных поставок...
        </div>
      </div>
    )
  }

  return (
    <>
      <div className="relative">
        {/* V2 Таблица товарных поставок */}
        <Table>
          <TableHeaderV2Block userRole={userRole} />
          
          <TableBody>
            {supplies.length > 0 &&
              supplies.map((supply, index) => {
                // Защита от неполных данных
                if (!supply.seller) {
                  console.warn('⚠️ V2 Supply without seller:', supply.id)
                  return null
                }

                const isSupplyExpanded = expansionState.expandedSupplies.has(supply.id)
                const inputValues = inputManagement.inputValues[supply.id] || { volume: '', packages: '' }

                return (
                  <React.Fragment key={supply.id}>
                    {/* УРОВЕНЬ 1: Основная строка V2 товарной поставки */}
                    <SupplyRowV2Block
                      supply={supply}
                      index={index}
                      userRole={userRole}
                      isExpanded={isSupplyExpanded}
                      inputValues={inputValues}
                      pendingUpdates={inputManagement.pendingUpdates}
                      onToggleExpansion={expansionState.toggleSupplyExpansion}
                      onVolumeChange={(value) => inputManagement.handleVolumeChange(supply.id, value)}
                      onPackagesChange={(value) => inputManagement.handlePackagesChange(supply.id, value)}
                      onVolumeBlur={() => inputManagement.handleVolumeBlur(supply.id)}
                      onPackagesBlur={() => inputManagement.handlePackagesBlur(supply.id)}
                      onSupplyAction={onSupplyAction}
                      onRightClick={contextMenu.handleRightClick}
                    />

                    {/* TODO: УРОВЕНЬ 2-5 будут добавлены в следующих итерациях V2 */}
                    {/* - Уровень 2: Детали товаров с V2 рецептурами */}
                    {/* - Уровень 3: Компоненты рецептур (материалы) */}
                    {/* - Уровень 4: Услуги рецептур */}
                    {/* - Уровень 5: Запросы услуг фулфилмента */}
                  </React.Fragment>
                )
              })}
          </TableBody>
        </Table>
      </div>

      {/* Контекстное меню и диалоги (общие с V1) */}
      <ContextMenu
        isOpen={contextMenu.contextMenu.isOpen}
        position={contextMenu.contextMenu.position}
        onClose={contextMenu.handleCloseContextMenu}
        onCancel={contextMenu.handleCancelFromContextMenu}
      />

      <CancelConfirmDialog
        isOpen={contextMenu.cancelDialogOpen}
        onClose={() => contextMenu.setCancelDialogOpen(false)}
        onConfirm={contextMenu.handleConfirmCancel}
        supplyId={contextMenu.contextMenu.supplyId}
      />
    </>
  )
}