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

import { Badge } from '@/components/ui/badge'
import { formatCurrency } from '@/lib/utils'

import { useTableUtils } from '../hooks/useTableUtils'
import type { SupplyRowBlockProps } from '../types'

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

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

  // Вычисляемые поля для уровня 1 (агрегированные данные)
  const getSupplyAggregatedData = () => {
    const items = supply.items || []
    const routes = supply.routes || []

    const orderedTotal = items.reduce((sum, item) => sum + (item.quantity || 0), 0)
    const deliveredTotal = 0 // Пока нет данных о поставленном количестве
    const defectTotal = 0 // Пока нет данных о браке

    const goodsPrice = items.reduce((sum, item) => sum + (item.totalPrice || 0), 0)

    // Расчет услуг ФФ по формуле из CartBlock.tsx
    const servicesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.services) return sum

      const itemServicesPrice = recipe.services.reduce((serviceSum, service) => {
        return serviceSum + service.price * item.quantity
      }, 0)

      return sum + itemServicesPrice
    }, 0)

    // Расчет расходников ФФ
    const ffConsumablesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.fulfillmentConsumables) return sum

      const itemFFConsumablesPrice = recipe.fulfillmentConsumables.reduce((consumableSum, consumable) => {
        return consumableSum + consumable.price * item.quantity
      }, 0)

      return sum + itemFFConsumablesPrice
    }, 0)

    // Расчет расходников селлера
    const sellerConsumablesPrice = items.reduce((sum, item) => {
      const recipe = item.recipe
      if (!recipe?.sellerConsumables) return sum

      const itemSellerConsumablesPrice = recipe.sellerConsumables.reduce((consumableSum, consumable) => {
        return consumableSum + consumable.price * item.quantity
      }, 0)

      return sum + itemSellerConsumablesPrice
    }, 0)

    const logisticsPrice = routes.reduce((sum, route) => sum + (route.price || 0), 0)
    const total = goodsPrice + servicesPrice + ffConsumablesPrice + sellerConsumablesPrice + logisticsPrice

    return {
      orderedTotal,
      deliveredTotal,
      defectTotal,
      goodsPrice,
      servicesPrice,
      ffConsumablesPrice,
      sellerConsumablesPrice,
      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>
          )
        }
        break

      case 'LOGIST': // Логист
        if (status === '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, 'confirm_logistics')
              }}
            >
              Подтвердить
            </button>
          )
        }
        break

      default:
        return null
    }

    return null
  }

  const aggregatedData = getSupplyAggregatedData()

  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.partner.name || supply.partner.fullName}
            </span>
            <span className="text-white/50 text-[10px]">
              {supply.partner.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.deliveryDate)}
        </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.deliveredTotal}
            </span>
          </TableCell>
          <TableCell>
            <span className="text-red-400 font-mono text-sm">
              {aggregatedData.defectTotal}
            </span>
          </TableCell>
        </>
      )}

      {/* Цена товаров */}
      <TableCell>
        <span className="text-white font-mono text-sm">
          {formatCurrency(aggregatedData.goodsPrice)}
        </span>
      </TableCell>

      {/* Объём и Грузовые места (только для WHOLESALE, FULFILLMENT, LOGIST) */}
      {(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.volume ? `${supply.volume} м³` : '-'}
              </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) */}
      {userRole !== 'WHOLESALE' && (
        <>
          <TableCell className="hidden lg:table-cell">
            <span className="text-blue-400 font-mono text-sm">
              {formatCurrency(aggregatedData.servicesPrice)}
            </span>
          </TableCell>
          <TableCell className="hidden lg:table-cell">
            <span className="text-green-400 font-mono text-sm">
              {formatCurrency(aggregatedData.ffConsumablesPrice)}
            </span>
          </TableCell>
          <TableCell className="hidden lg:table-cell">
            <span className="text-yellow-400 font-mono text-sm">
              {formatCurrency(aggregatedData.sellerConsumablesPrice)}
            </span>
          </TableCell>
          <TableCell className="hidden lg:table-cell">
            <span className="text-purple-400 font-mono text-sm">
              {formatCurrency(aggregatedData.logisticsPrice)}
            </span>
          </TableCell>
          <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>
  )
})