import { Package, ChevronDown, ChevronRight } from 'lucide-react'
import React from 'react'

import { formatCurrency } from '@/lib/utils'

import { useTableUtils } from '../hooks/useTableUtils'
import type { SupplyRowV2BlockProps } from '../types/v2-types'

import { ActionButtons } from './ActionButtons'
import { StatusBadge } from './StatusBadge'
import { TableRow, TableCell } from './TableComponents'

// Компонент основной строки товарной поставки V2 (УРОВЕНЬ 1)
export const SupplyRowV2Block = React.memo(function SupplyRowV2Block({
  supply,
  index,
  userRole,
  isExpanded,
  inputValues,
  pendingUpdates,
  onToggleExpansion,
  onVolumeChange,
  onPackagesChange,
  onVolumeBlur,
  onPackagesBlur,
  onSupplyAction,
  onRightClick,
}: SupplyRowV2BlockProps) {
  const { getSupplyColor, getLevelBackgroundColor, formatDate } = useTableUtils()

  // Вычисляемые поля для V2 товарных поставок
  const getSupplyV2AggregatedData = () => {
    const items = supply.items || []
    const requestedServices = supply.requestedServices || []

    // Количества
    const orderedTotal = items.reduce((sum, item) => sum + (item.quantity || 0), 0)
    const receivedTotal = items.reduce((sum, item) => sum + (item.receivedQuantity || 0), 0)
    const damagedTotal = items.reduce((sum, item) => sum + (item.damagedQuantity || 0), 0)

    // Стоимости (с учетом ролевой безопасности)
    let goodsPrice = 0
    let servicesPrice = 0
    let recipeComponentsPrice = 0
    let recipeServicesPrice = 0

    // Товары - цены видят только SELLER и WHOLESALE
    if (userRole === 'SELLER' || userRole === 'WHOLESALE') {
      goodsPrice = items.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
    }

    // Услуги фулфилмента - не видят WHOLESALE и LOGIST
    if (userRole !== 'WHOLESALE' && userRole !== 'LOGIST') {
      servicesPrice = requestedServices.reduce((sum, service) => sum + (service.totalPrice || 0), 0)
    }

    // Компоненты и услуги из рецептур - не видят WHOLESALE
    if (userRole !== 'WHOLESALE') {
      recipeComponentsPrice = items.reduce((sum, item) => {
        if (!item.recipe) return sum
        
        const componentsCost = item.recipe.components.reduce((componentSum, component) => 
          componentSum + (component.cost * item.quantity), 0)
        
        return sum + componentsCost
      }, 0)

      recipeServicesPrice = items.reduce((sum, item) => {
        if (!item.recipe) return sum
        
        const servicesCost = item.recipe.services.reduce((serviceSum, service) => 
          serviceSum + (service.totalPrice * item.quantity), 0)
        
        return sum + servicesCost
      }, 0)
    }

    // Логистика - не видят WHOLESALE
    const logisticsPrice = userRole !== 'WHOLESALE' ? (supply.logisticsCost || 0) : 0

    const total = goodsPrice + servicesPrice + recipeComponentsPrice + recipeServicesPrice + logisticsPrice

    return {
      orderedTotal,
      receivedTotal,
      damagedTotal,
      goodsPrice,
      servicesPrice,
      recipeComponentsPrice,
      recipeServicesPrice,
      logisticsPrice,
      total,
    }
  }

  // Условные кнопки действий в зависимости от роли и статуса
  const renderActionButtons = () => {
    const { status } = supply

    switch (userRole) {
      case 'WHOLESALE': // Поставщик
        if (status === 'PENDING') {
          return <ActionButtons supplyId={supply.id} onSupplyAction={onSupplyAction} />
        }
        break

      case 'FULFILLMENT': // Фулфилмент
        if (status === 'SUPPLIER_APPROVED') {
          return (
            <button
              className="bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 border border-blue-500/30 px-3 py-1 rounded text-sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(supply.id, 'accept')
              }}
            >
              Принять
            </button>
          )
        }
        if (status === 'IN_TRANSIT') {
          return (
            <button
              className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30 px-3 py-1 rounded text-sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(supply.id, 'receive')
              }}
            >
              Принять товар
            </button>
          )
        }
        break

      case 'LOGIST': // Логист
        if (status === 'LOGISTICS_CONFIRMED') {
          return (
            <button
              className="bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 border border-purple-500/30 px-3 py-1 rounded text-sm"
              onClick={(e) => {
                e.stopPropagation()
                onSupplyAction?.(supply.id, 'ship')
              }}
            >
              Отгрузить
            </button>
          )
        }
        break

      default:
        return null
    }

    return null
  }

  const aggregatedData = getSupplyV2AggregatedData()

  return (
    <TableRow
      className="border-white/10 hover:bg-white/5 cursor-pointer transition-colors"
      style={{
        backgroundColor: getLevelBackgroundColor(1, index),
      }}
      onClick={() => onToggleExpansion(supply.id)}
      onContextMenu={(e) => onRightClick(e, supply.id)}
    >
      {/* Колонка с номером поставки и иконкой раскрытия */}
      <TableCell className="relative">
        <div className="flex items-center space-x-2">
          {isExpanded ? (
            <ChevronDown className="h-4 w-4 text-white/60" />
          ) : (
            <ChevronRight className="h-4 w-4 text-white/60" />
          )}
          <Package className="h-4 w-4" style={{ color: getSupplyColor(index) }} />
          <span className="text-white font-medium text-sm">
            #{supply.id.slice(-4).toUpperCase()}
          </span>
          
          {/* Селлер в той же колонке для компактности */}
          <div className="ml-2 flex flex-col">
            <span className="text-white/80 text-xs">
              {supply.seller.name || supply.seller.fullName}
            </span>
            <span className="text-white/50 text-[10px]">
              {supply.seller.inn}
            </span>
          </div>
        </div>
        
        {/* Вертикальная полоса цвета поставки */}
        <div
          className="absolute left-0 top-0 w-0.5 h-full"
          style={{ backgroundColor: getSupplyColor(index) }}
        ></div>
      </TableCell>

      {/* Дата поставки */}
      <TableCell>
        <span className="text-white/80 text-sm">
          {formatDate(supply.requestedDeliveryDate)}
        </span>
      </TableCell>

      {/* Заказано */}
      <TableCell>
        <span className="text-white font-mono text-sm">
          {aggregatedData.orderedTotal}
        </span>
      </TableCell>

      {/* Получено и Брак (только не для WHOLESALE) */}
      {userRole !== 'WHOLESALE' && (
        <>
          <TableCell>
            <span className="text-green-400 font-mono text-sm">
              {aggregatedData.receivedTotal}
            </span>
          </TableCell>
          <TableCell>
            <span className="text-red-400 font-mono text-sm">
              {aggregatedData.damagedTotal}
            </span>
          </TableCell>
        </>
      )}

      {/* Цена товаров (только для SELLER и WHOLESALE) */}
      <TableCell>
        {userRole === 'SELLER' || userRole === 'WHOLESALE' ? (
          <span className="text-white font-mono text-sm">
            {formatCurrency(aggregatedData.goodsPrice)}
          </span>
        ) : (
          <span className="text-white/50 text-sm">-</span>
        )}
      </TableCell>

      {/* Объём и Грузовые места (редактируемые для WHOLESALE) */}
      {(userRole === 'WHOLESALE' || userRole === 'FULFILLMENT' || userRole === 'LOGIST') && (
        <>
          <TableCell>
            {userRole === 'WHOLESALE' ? (
              <input
                type="number"
                step="0.1"
                placeholder="м³"
                value={inputValues.volume}
                onChange={(e) => onVolumeChange(e.target.value)}
                onBlur={onVolumeBlur}
                className="w-16 bg-gray-800/50 border border-white/20 rounded px-2 py-1 text-white text-xs"
                onClick={(e) => e.stopPropagation()}
              />
            ) : (
              <span className="text-white/70 font-mono text-sm">
                {supply.estimatedVolume ? `${supply.estimatedVolume} м³` : '-'}
              </span>
            )}
          </TableCell>
          <TableCell>
            {userRole === 'WHOLESALE' ? (
              <input
                type="number"
                placeholder="шт"
                value={inputValues.packages}
                onChange={(e) => onPackagesChange(e.target.value)}
                onBlur={onPackagesBlur}
                className="w-16 bg-gray-800/50 border border-white/20 rounded px-2 py-1 text-white text-xs"
                onClick={(e) => e.stopPropagation()}
              />
            ) : (
              <span className="text-white/70 font-mono text-sm">
                {supply.packagesCount || '-'}
              </span>
            )}
          </TableCell>
        </>
      )}

      {/* Услуги ФФ (не для WHOLESALE и LOGIST) */}
      {userRole !== 'WHOLESALE' && userRole !== 'LOGIST' && (
        <TableCell className="hidden lg:table-cell">
          <span className="text-blue-400 font-mono text-sm">
            {formatCurrency(aggregatedData.servicesPrice)}
          </span>
        </TableCell>
      )}

      {/* Компоненты рецептур (не для WHOLESALE) */}
      {userRole !== 'WHOLESALE' && (
        <TableCell className="hidden lg:table-cell">
          <span className="text-green-400 font-mono text-sm">
            {formatCurrency(aggregatedData.recipeComponentsPrice)}
          </span>
        </TableCell>
      )}

      {/* Услуги рецептур (не для WHOLESALE) */}
      {userRole !== 'WHOLESALE' && (
        <TableCell className="hidden lg:table-cell">
          <span className="text-yellow-400 font-mono text-sm">
            {formatCurrency(aggregatedData.recipeServicesPrice)}
          </span>
        </TableCell>
      )}

      {/* Логистика (не для WHOLESALE) */}
      {userRole !== 'WHOLESALE' && (
        <TableCell className="hidden lg:table-cell">
          <span className="text-purple-400 font-mono text-sm">
            {formatCurrency(aggregatedData.logisticsPrice)}
          </span>
        </TableCell>
      )}

      {/* Итого (не для WHOLESALE) */}
      {userRole !== 'WHOLESALE' && (
        <TableCell>
          <span className="text-white font-semibold font-mono">
            {formatCurrency(aggregatedData.total)}
          </span>
        </TableCell>
      )}

      {/* Статус */}
      <TableCell>
        <StatusBadge status={supply.status} />
      </TableCell>

      {/* Действия (в зависимости от роли и статуса) */}
      <TableCell onClick={(e) => e.stopPropagation()}>
        {renderActionButtons()}
      </TableCell>
    </TableRow>
  )
})