'use client'

import { useQuery, useMutation } from '@apollo/client'
import {
  Calendar,
  Package,
  Truck,
  CheckCircle,
  Clock,
  XCircle,
  MapPin,
  Phone,
  Mail,
  Layers,
  Building,
  Hash,
  Store,
  UserPlus,
  Settings,
} from 'lucide-react'
import React, { useState } from 'react'
import { toast } from 'sonner'

import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { ASSIGN_LOGISTICS_TO_SUPPLY, FULFILLMENT_RECEIVE_ORDER } from '@/graphql/mutations'
import {
  GET_SUPPLY_ORDERS,
  GET_PENDING_SUPPLIES_COUNT,
  GET_WAREHOUSE_PRODUCTS,
  GET_LOGISTICS_PARTNERS,
} from '@/graphql/queries'
import { GET_MY_EMPLOYEES_V2 } from '@/graphql/queries/employees-v2'
import { GET_MY_FULFILLMENT_CONSUMABLES_V2 } from '@/graphql/queries/fulfillment-services-v2'
import { GET_INCOMING_SELLER_SUPPLIES } from '@/graphql/queries/seller-consumables-v2'
import { useAuthContext } from '@/contexts/AuthContext'

interface SupplyOrder {
  id: string
  partnerId: string
  deliveryDate: string
  status:
    | 'PENDING'
    | 'SUPPLIER_APPROVED'
    | 'CONFIRMED'
    | 'LOGISTICS_CONFIRMED'
    | 'SHIPPED'
    | 'IN_TRANSIT'
    | 'DELIVERED'
    | 'CANCELLED'
  totalAmount: number
  totalItems: number
  createdAt: string
  consumableType?: string // Добавлено для фильтрации типа поставки
  fulfillmentCenter?: {
    id: string
    name: string
    fullName: string
  }
  organization?: {
    id: string
    name: string
    fullName: string
  }
  partner: {
    id: string
    inn: string
    name: string
    fullName: string
    address?: string
    phones?: string[]
    emails?: string[]
  }
  logisticsPartner?: {
    id: string
    name: string
    fullName: string
    type: string
  }
  items: Array<{
    id: string
    quantity: number
    price: number
    totalPrice: number
    recipe?: {
      services?: Array<{ id: string; name: string }>
      fulfillmentConsumables?: Array<{ id: string; name: string }>
      sellerConsumables?: Array<{ id: string; name: string }>
      marketplaceCardId?: string
    }
    product: {
      id: string
      name: string
      article: string
      description?: string
      price: number
      quantity: number
      images?: string[]
      mainImage?: string
      category?: {
        id: string
        name: string
      }
    }
  }>
}

export function FulfillmentConsumablesOrdersTab() {
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set())
  const [assigningOrders, setAssigningOrders] = useState<Set<string>>(new Set())
  const [selectedLogistics, setSelectedLogistics] = useState<{
    [orderId: string]: string
  }>({})
  const [selectedEmployees, setSelectedEmployees] = useState<{
    [orderId: string]: string
  }>({})
  const { user } = useAuthContext()

  // Запросы данных
  const { data: employeesData, loading: employeesLoading, error: employeesError } = useQuery(GET_MY_EMPLOYEES_V2)
  const { data: logisticsData, loading: logisticsLoading, error: logisticsError } = useQuery(GET_LOGISTICS_PARTNERS)

  // Отладочная информация
  console.warn('DEBUG EMPLOYEES:', {
    loading: employeesLoading,
    error: employeesError?.message,
    errorDetails: employeesError,
    data: employeesData,
    employees: employeesData?.employeesV2?.items,
  })
  console.warn('DEBUG LOGISTICS:', {
    loading: logisticsLoading,
    error: logisticsError?.message,
    errorDetails: logisticsError,
    data: logisticsData,
    partners: logisticsData?.logisticsPartners,
  })

  // Логируем ошибки отдельно
  if (employeesError) {
    console.error('EMPLOYEES ERROR:', employeesError)
  }
  if (logisticsError) {
    console.error('LOGISTICS ERROR:', logisticsError)
  }

  // Загружаем заказы поставок из старой системы
  const { data, loading, error, refetch } = useQuery(GET_SUPPLY_ORDERS)

  // Загружаем селлерские поставки из новой системы
  const { 
    data: sellerData, 
    loading: sellerLoading, 
    error: sellerError, 
    refetch: refetchSellerSupplies, 
  } = useQuery(GET_INCOMING_SELLER_SUPPLIES)

  // Мутация для приемки поставки фулфилментом
  const [fulfillmentReceiveOrder, { loading: receiving }] = useMutation(FULFILLMENT_RECEIVE_ORDER, {
    onCompleted: (data) => {
      if (data.fulfillmentReceiveOrder.success) {
        toast.success(data.fulfillmentReceiveOrder.message)
        refetch() // Обновляем старые заказы поставок
        refetchSellerSupplies() // Обновляем селлерские поставки
      } else {
        toast.error(data.fulfillmentReceiveOrder.message)
      }
    },
    refetchQueries: [
      { query: GET_SUPPLY_ORDERS }, // Обновляем заказы поставок
      { query: GET_INCOMING_SELLER_SUPPLIES }, // Обновляем селлерские поставки
      { query: GET_MY_FULFILLMENT_CONSUMABLES_V2 }, // Обновляем склад фулфилмента (расходники фулфилмента)
      { query: GET_WAREHOUSE_PRODUCTS }, // Обновляем товары склада
      { query: GET_PENDING_SUPPLIES_COUNT }, // Обновляем счетчики уведомлений
    ],
    onError: (error) => {
      console.error('Error receiving supply order:', error)
      toast.error('Ошибка при приеме заказа поставки')
    },
  })

  // Мутация для назначения логистики и ответственного
  const [assignLogisticsToSupply, { loading: assigning }] = useMutation(ASSIGN_LOGISTICS_TO_SUPPLY, {
    onCompleted: (data) => {
      if (data.assignLogisticsToSupply.success) {
        toast.success('Логистика и ответственный назначены успешно')
        refetch() // Обновляем старые заказы поставок
        refetchSellerSupplies() // Обновляем селлерские поставки
        // Сбрасываем состояние назначения
        setAssigningOrders((prev) => {
          const newSet = new Set(prev)
          newSet.delete(data.assignLogisticsToSupply.supplyOrder.id)
          return newSet
        })
      } else {
        toast.error(data.assignLogisticsToSupply.message || 'Ошибка при назначении логистики')
      }
    },
    refetchQueries: [
      { query: GET_SUPPLY_ORDERS },
      { query: GET_INCOMING_SELLER_SUPPLIES },
    ],
    onError: (error) => {
      console.error('Error assigning logistics:', error)
      toast.error('Ошибка при назначении логистики')
    },
  })

  const toggleOrderExpansion = (orderId: string) => {
    const newExpanded = new Set(expandedOrders)
    if (newExpanded.has(orderId)) {
      newExpanded.delete(orderId)
    } else {
      newExpanded.add(orderId)
    }
    setExpandedOrders(newExpanded)
  }

  // Получаем данные заказов поставок из старой системы
  const supplyOrders: SupplyOrder[] = data?.supplyOrders || []
  
  // Получаем селлерские поставки и конвертируем их в формат SupplyOrder
  const sellerSupplies = sellerData?.incomingSellerSupplies || []
  const convertedSellerSupplies: SupplyOrder[] = sellerSupplies.map((supply: any) => ({
    id: supply.id,
    partnerId: supply.supplierId || supply.supplier?.id,
    deliveryDate: supply.requestedDeliveryDate,
    status: supply.status === 'DELIVERED' ? 'DELIVERED' : 
            supply.status === 'SHIPPED' ? 'SHIPPED' : 
            supply.status === 'APPROVED' ? 'SUPPLIER_APPROVED' : 
            'PENDING',
    totalAmount: supply.totalCostWithDelivery || supply.items?.reduce((sum: number, item: any) => 
      sum + (item.unitPrice * item.requestedQuantity), 0) || 0,
    totalItems: supply.items?.reduce((sum: number, item: any) => sum + item.requestedQuantity, 0) || 0,
    createdAt: supply.createdAt,
    consumableType: 'SELLER_CONSUMABLES',
    fulfillmentCenter: supply.fulfillmentCenter,
    organization: supply.seller, // Селлер-создатель
    partner: supply.supplier, // Поставщик
    logisticsPartner: supply.logisticsPartner,
    items: supply.items?.map((item: any) => ({
      id: item.id,
      quantity: item.requestedQuantity,
      price: item.unitPrice,
      totalPrice: item.totalPrice || (item.unitPrice * item.requestedQuantity),
      product: {
        id: item.product?.id,
        name: item.product?.name || 'Товар',
        article: item.product?.article || '',
        description: item.product?.description,
        price: item.product?.price,
        quantity: item.product?.quantity,
        images: item.product?.images,
        mainImage: item.product?.mainImage,
        category: item.product?.category,
      },
    })) || [],
  }))

  // Объединяем старые поставки и селлерские поставки
  const allSupplyOrders = [...supplyOrders, ...convertedSellerSupplies]

  // Фильтруем заказы для фулфилмента (расходники фулфилмента + селлеров)
  const fulfillmentOrders = supplyOrders.filter((order) => {
    // Получатель должен быть наш фулфилмент-центр
    const isRecipient = order.fulfillmentCenter?.id === user?.organization?.id
    // И статус не PENDING и не CANCELLED (одобренные поставщиком заявки)
    const isApproved = order.status !== 'CANCELLED' && order.status !== 'PENDING'
    
    // ✅ ИСПРАВЛЕНИЕ: Показывать ОБА типа расходников - фулфилмент и селлер
    const isFulfillmentConsumables = order.consumableType === 'FULFILLMENT_CONSUMABLES'
    const isSellerConsumables = order.consumableType === 'SELLER_CONSUMABLES'
    const isAnyConsumables = isFulfillmentConsumables || isSellerConsumables
    
    // Проверяем, что это НЕ товары (товары содержат услуги в рецептуре)
    const hasServices = order.items?.some(item => item.recipe?.services && item.recipe.services.length > 0)
    const isConsumablesOnly = isAnyConsumables && !hasServices
    
    // Дополнительная проверка для селлерских поставок
    const isCreatedBySelf = order.organization?.id === user?.organization?.id
    const isFromSeller = order.organization?.type === 'SELLER'
    
    // Логика фильтрации:
    // 1. Свои поставки фулфилмента (созданные нами)
    // 2. Поставки от селлеров (созданные селлерами для нас)
    const shouldShow = isRecipient && isApproved && isConsumablesOnly && (isCreatedBySelf || isFromSeller)

    console.warn('🔍 Фильтрация расходников фулфилмента + селлеров:', {
      orderId: order.id.slice(-8),
      isRecipient,
      isApproved,
      isFulfillmentConsumables,
      isSellerConsumables,
      isAnyConsumables,
      hasServices,
      isConsumablesOnly,
      isCreatedBySelf,
      isFromSeller,
      consumableType: order.consumableType,
      organizationType: order.organization?.type,
      itemsWithServices: order.items?.filter(item => item.recipe?.services && item.recipe.services.length > 0).length || 0,
      finalResult: shouldShow,
    })

    return shouldShow
  })

  // Генерируем порядковые номера для заказов
  const ordersWithNumbers = fulfillmentOrders.map((order, index) => ({
    ...order,
    number: fulfillmentOrders.length - index, // Обратный порядок для новых заказов сверху
  }))

  // Автоматически открываем режим назначения для заказов, которые требуют назначения логистики
  React.useEffect(() => {
    fulfillmentOrders.forEach((order) => {
      if (canAssignLogistics(order) && !assigningOrders.has(order.id)) {
        setAssigningOrders((prev) => {
          const newSet = new Set(prev)
          newSet.add(order.id)
          return newSet
        })
      }
    })
  }, [fulfillmentOrders])

  const getStatusBadge = (status: SupplyOrder['status']) => {
    const statusMap = {
      PENDING: {
        label: 'Ожидание',
        color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
        icon: Clock,
      },
      SUPPLIER_APPROVED: {
        label: 'Одобрено',
        color: 'bg-green-500/20 text-green-300 border-green-500/30',
        icon: CheckCircle,
      },
      CONFIRMED: {
        label: 'Подтверждена',
        color: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30',
        icon: CheckCircle,
      },
      LOGISTICS_CONFIRMED: {
        label: 'Логистика OK',
        color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
        icon: Truck,
      },
      SHIPPED: {
        label: 'Отгружено',
        color: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
        icon: Package,
      },
      IN_TRANSIT: {
        label: 'В пути',
        color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30',
        icon: Truck,
      },
      DELIVERED: {
        label: 'Доставлена',
        color: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
        icon: Package,
      },
      CANCELLED: {
        label: 'Отменена',
        color: 'bg-red-500/20 text-red-300 border-red-500/30',
        icon: XCircle,
      },
    }
    const { label, color, icon: Icon } = statusMap[status]
    return (
      <Badge className={`${color} border flex items-center gap-1 text-xs`}>
        <Icon className="h-3 w-3" />
        {label}
      </Badge>
    )
  }

  // Функция для приема заказа фулфилментом
  const handleReceiveOrder = async (orderId: string) => {
    try {
      await fulfillmentReceiveOrder({
        variables: { id: orderId },
      })
    } catch (error) {
      console.error('Error receiving order:', error)
    }
  }

  // Проверяем, можно ли принять заказ (для фулфилмента)
  const canReceiveOrder = (status: SupplyOrder['status']) => {
    return status === 'SHIPPED'
  }

  const toggleAssignmentMode = (orderId: string) => {
    setAssigningOrders((prev) => {
      const newSet = new Set(prev)
      if (newSet.has(orderId)) {
        newSet.delete(orderId)
      } else {
        newSet.add(orderId)
      }
      return newSet
    })
  }

  const handleAssignLogistics = async (orderId: string) => {
    const logisticsId = selectedLogistics[orderId]
    const employeeId = selectedEmployees[orderId]

    if (!logisticsId) {
      toast.error('Выберите логистическую компанию')
      return
    }

    if (!employeeId) {
      toast.error('Выберите ответственного сотрудника')
      return
    }

    try {
      await assignLogisticsToSupply({
        variables: {
          supplyOrderId: orderId,
          logisticsPartnerId: logisticsId,
          responsibleId: employeeId,
        },
      })
    } catch (error) {
      console.error('Error assigning logistics:', error)
    }
  }

  const canAssignLogistics = (order: SupplyOrder) => {
    // Можем назначать логистику если:
    // 1. Статус SUPPLIER_APPROVED (одобрено поставщиком) или CONFIRMED (подтвержден фулфилментом)
    // 2. Логистика еще не назначена
    return (order.status === 'SUPPLIER_APPROVED' || order.status === 'CONFIRMED') && !order.logisticsPartner
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
    }).format(amount)
  }

  const getInitials = (name: string): string => {
    return name
      .split(' ')
      .map((word) => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-white/60">Загрузка заказов поставок...</div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-red-400">Ошибка загрузки заказов поставок</div>
      </div>
    )
  }

  return (
    <div className="space-y-2">
      {/* Компактная статистика */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
        <Card className="bg-white/10 backdrop-blur border-white/20 p-2">
          <div className="flex items-center space-x-2">
            <div className="p-1 bg-green-500/20 rounded">
              <CheckCircle className="h-3 w-3 text-green-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Одобрено</p>
              <p className="text-sm font-bold text-white">
                {(fulfillmentOrders || []).filter((order) => order.status === 'SUPPLIER_APPROVED').length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-2">
          <div className="flex items-center space-x-2">
            <div className="p-1 bg-emerald-500/20 rounded">
              <CheckCircle className="h-3 w-3 text-emerald-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Подтверждено</p>
              <p className="text-sm font-bold text-white">
                {(fulfillmentOrders || []).filter((order) => order.status === 'CONFIRMED').length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-2">
          <div className="flex items-center space-x-2">
            <div className="p-1 bg-yellow-500/20 rounded">
              <Truck className="h-3 w-3 text-yellow-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">В пути</p>
              <p className="text-sm font-bold text-white">
                {(fulfillmentOrders || []).filter((order) => order.status === 'IN_TRANSIT').length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-2">
          <div className="flex items-center space-x-2">
            <div className="p-1 bg-purple-500/20 rounded">
              <Package className="h-3 w-3 text-purple-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Доставлено</p>
              <p className="text-sm font-bold text-white">
                {(fulfillmentOrders || []).filter((order) => order.status === 'DELIVERED').length}
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* Оптимизированный список заказов поставок */}
      <div className="space-y-1.5">
        {ordersWithNumbers.length === 0 ? (
          <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
            <div className="text-center">
              <Package className="h-8 w-8 text-white/40 mx-auto mb-2" />
              <h3 className="text-sm font-semibold text-white mb-1">Нет заказов поставок</h3>
              <p className="text-white/60 text-xs">Заказы поставок расходников будут отображаться здесь</p>
            </div>
          </Card>
        ) : (
          ordersWithNumbers.map((order) => (
            <Card
              key={order.id}
              className={`bg-white/10 backdrop-blur border-white/20 overflow-hidden hover:bg-white/15 transition-colors ${
                canAssignLogistics(order) && assigningOrders.has(order.id) ? 'cursor-default' : 'cursor-pointer'
              }`}
              onClick={() => {
                if (!(canAssignLogistics(order) && assigningOrders.has(order.id))) {
                  toggleOrderExpansion(order.id)
                }
              }}
            >
              {/* Компактная основная информация */}
              <div className="px-3 py-2">
                <div className="flex items-center justify-between">
                  {/* Левая часть - основная информация */}
                  <div className="flex items-center space-x-3 flex-1 min-w-0">
                    {/* Номер поставки */}
                    <div className="flex items-center space-x-1">
                      <Hash className="h-3 w-3 text-white/60 flex-shrink-0" />
                      <span className="text-white font-semibold text-sm">{order.number}</span>
                    </div>

                    {/* Заказчик (селлер или фулфилмент) */}
                    <div className="flex items-center space-x-2 min-w-0">
                      <div className="flex flex-col items-center">
                        <Store className="h-3 w-3 text-blue-400 mb-0.5" />
                        <span className="text-blue-400 text-xs font-medium leading-none">
                          {order.consumableType === 'SELLER_CONSUMABLES' ? 'Селлер' : 'Заказчик'}
                        </span>
                      </div>
                      <div className="flex items-center space-x-1.5">
                        <Avatar className="w-7 h-7 flex-shrink-0">
                          <AvatarFallback className="bg-blue-500 text-white text-xs">
                            {getInitials(order.organization?.name || order.organization?.fullName || 'Н/Д')}
                          </AvatarFallback>
                        </Avatar>
                        <div className="min-w-0 flex-1">
                          <h3 className="text-white font-medium text-sm truncate max-w-[120px]">
                            {order.organization?.name || order.organization?.fullName || 'Не указано'}
                          </h3>
                          <p className="text-white/60 text-xs">{order.organization?.type || 'Н/Д'}</p>
                        </div>
                      </div>
                    </div>

                    {/* Поставщик */}
                    <div className="hidden xl:flex items-center space-x-2 min-w-0">
                      <div className="flex flex-col items-center">
                        <Building className="h-3 w-3 text-green-400 mb-0.5" />
                        <span className="text-green-400 text-xs font-medium leading-none">Поставщик</span>
                      </div>
                      <div className="flex items-center space-x-1.5">
                        <Avatar className="w-7 h-7 flex-shrink-0">
                          <AvatarFallback className="bg-green-500 text-white text-xs">
                            {getInitials(order.partner.name || order.partner.fullName)}
                          </AvatarFallback>
                        </Avatar>
                        <div className="min-w-0">
                          <h3 className="text-white font-medium text-sm truncate max-w-[100px]">
                            {order.partner.name || order.partner.fullName}
                          </h3>
                          <p className="text-white/60 text-xs">{order.partner.inn}</p>
                        </div>
                      </div>
                    </div>

                    {/* Краткие данные */}
                    <div className="hidden lg:flex items-center space-x-4">
                      <div className="flex items-center space-x-1">
                        <Calendar className="h-3 w-3 text-blue-400" />
                        <span className="text-white text-xs">{formatDate(order.deliveryDate)}</span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Package className="h-3 w-3 text-green-400" />
                        <span className="text-white text-xs">{order.totalItems}</span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Layers className="h-3 w-3 text-purple-400" />
                        <span className="text-white text-xs">{order.items.length}</span>
                      </div>
                    </div>
                  </div>

                  {/* Правая часть - статус и действия */}
                  <div className="flex items-center space-x-2 flex-shrink-0">
                    {getStatusBadge(order.status)}

                    {canReceiveOrder(order.status) && (
                      <Button
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleReceiveOrder(order.id)
                        }}
                        disabled={receiving}
                        className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30 text-xs px-2 py-1 h-7"
                      >
                        <CheckCircle className="h-3 w-3 mr-1" />
                        Принять
                      </Button>
                    )}
                  </div>
                </div>

                {/* Мобильная версия поставщика и кратких данных */}
                <div className="xl:hidden mt-2 space-y-1">
                  {/* Поставщик на мобильных */}
                  <div className="flex items-center space-x-2">
                    <div className="flex flex-col items-center">
                      <Building className="h-3 w-3 text-green-400 mb-0.5" />
                      <span className="text-green-400 text-xs font-medium leading-none">Поставщик</span>
                    </div>
                    <div className="flex items-center space-x-1.5">
                      <Avatar className="w-6 h-6 flex-shrink-0">
                        <AvatarFallback className="bg-green-500 text-white text-xs">
                          {getInitials(order.partner.name || order.partner.fullName)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="min-w-0">
                        <h3 className="text-white font-medium text-sm truncate">
                          {order.partner.name || order.partner.fullName}
                        </h3>
                      </div>
                    </div>
                  </div>

                  {/* Краткие данные на мобильных */}
                  <div className="lg:hidden flex items-center justify-between text-xs">
                    <div className="flex items-center space-x-3">
                      <div className="flex items-center space-x-1">
                        <Calendar className="h-3 w-3 text-blue-400" />
                        <span className="text-white">{formatDate(order.deliveryDate)}</span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Package className="h-3 w-3 text-green-400" />
                        <span className="text-white">{order.totalItems} шт.</span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Layers className="h-3 w-3 text-purple-400" />
                        <span className="text-white">{order.items.length} поз.</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Назначение логистики и ответственного в одной строке */}
                {assigningOrders.has(order.id) && canAssignLogistics(order) && (
                  <div className="mt-2 p-2 bg-blue-500/10 border border-blue-500/20 rounded">
                    <div className="flex items-center gap-3">
                      {/* Иконка и заголовок */}
                      <div className="flex items-center text-blue-300 text-xs font-medium whitespace-nowrap">
                        <Settings className="h-3 w-3 mr-1" />
                        Назначить:
                      </div>

                      {/* Выбор логистики */}
                      <div className="flex-1 min-w-0">
                        <select
                          value={selectedLogistics[order.id] || ''}
                          onChange={(e) => {
                            setSelectedLogistics((prev) => ({
                              ...prev,
                              [order.id]: e.target.value,
                            }))
                          }}
                          className="w-full bg-white/10 border border-white/20 text-white text-xs rounded px-2 py-1 focus:ring-2 focus:ring-blue-400/50 focus:border-blue-400/50 appearance-none"
                        >
                          <option value="" className="bg-gray-800 text-white">
                            {logisticsData?.logisticsPartners?.length > 0 ? 'Выберите логистику' : 'Нет логистики'}
                          </option>
                          {logisticsData?.logisticsPartners?.map((logistics: any) => (
                            <option key={logistics.id} value={logistics.id} className="bg-gray-800 text-white">
                              {logistics.name || logistics.fullName}
                            </option>
                          )) || []}
                        </select>
                      </div>

                      {/* Выбор ответственного */}
                      <div className="flex-1 min-w-0">
                        <select
                          value={selectedEmployees[order.id] || ''}
                          onChange={(e) => {
                            setSelectedEmployees((prev) => ({
                              ...prev,
                              [order.id]: e.target.value,
                            }))
                          }}
                          className="w-full bg-white/10 border border-white/20 text-white text-xs rounded px-2 py-1 focus:ring-2 focus:ring-blue-400/50 focus:border-blue-400/50 appearance-none"
                        >
                          <option value="" className="bg-gray-800 text-white">
                            {employeesData?.employeesV2?.items?.length > 0 ? 'Выберите ответственного' : 'Нет сотрудников'}
                          </option>
                          {employeesData?.employeesV2?.items?.map((employee: any) => (
                            <option key={employee.id} value={employee.id} className="bg-gray-800 text-white">
                              {employee.personalInfo.fullName}
                            </option>
                          )) || []}
                        </select>
                      </div>

                      {/* Кнопки действий */}
                      <div className="flex gap-1 flex-shrink-0">
                        <Button
                          size="sm"
                          onClick={() => handleAssignLogistics(order.id)}
                          disabled={assigning}
                          className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30 text-xs px-2 py-1 h-6"
                        >
                          <UserPlus className="h-3 w-3 mr-1" />
                          Принять
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => toggleAssignmentMode(order.id)}
                          className="border-white/20 text-white/60 hover:bg-white/10 text-xs px-2 py-1 h-6"
                        >
                          ✕
                        </Button>
                      </div>
                    </div>
                  </div>
                )}

                {/* Развернутые детали заказа */}
                {expandedOrders.has(order.id) && (
                  <>
                    <Separator className="my-2 bg-white/10" />

                    {/* Сумма заказа */}
                    <div className="mb-2 p-2 bg-white/5 rounded">
                      <div className="flex items-center justify-between">
                        <span className="text-white/60 text-sm">Общая сумма:</span>
                        <span className="text-white font-semibold text-base">{formatCurrency(order.totalAmount)}</span>
                      </div>
                    </div>

                    {/* Информация о заказчике */}
                    <div className="mb-3">
                      <h4 className="text-white font-semibold mb-1.5 flex items-center text-sm">
                        <Store className="h-4 w-4 mr-1.5 text-blue-400" />
                        Информация о {order.consumableType === 'SELLER_CONSUMABLES' ? 'селлере' : 'заказчике'}
                      </h4>
                      <div className="bg-white/5 rounded p-2 space-y-1.5">
                        <div className="flex items-center space-x-2">
                          <Building className="h-3 w-3 text-white/60 flex-shrink-0" />
                          <span className="text-white/80 text-sm font-medium">
                            {order.organization?.name || order.organization?.fullName || 'Не указано'}
                          </span>
                          <span className="text-white/60 text-xs">
                            ({order.organization?.type || 'Н/Д'})
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Информация о поставщике */}
                    <div className="mb-3">
                      <h4 className="text-white font-semibold mb-1.5 flex items-center text-sm">
                        <Building className="h-4 w-4 mr-1.5 text-green-400" />
                        Информация о поставщике
                      </h4>
                      <div className="bg-white/5 rounded p-2 space-y-1.5">
                        <div className="flex items-center space-x-2">
                          <Building className="h-3 w-3 text-white/60 flex-shrink-0" />
                          <span className="text-white/80 text-sm font-medium">
                            {order.partner.name || order.partner.fullName}
                          </span>
                          <span className="text-white/60 text-xs">
                            ИНН: {order.partner.inn}
                          </span>
                        </div>
                        {order.partner.address && (
                          <div className="flex items-center space-x-2">
                            <MapPin className="h-3 w-3 text-white/60 flex-shrink-0" />
                            <span className="text-white/80 text-sm">{order.partner.address}</span>
                          </div>
                        )}
                        {order.partner.phones && order.partner.phones.length > 0 && (
                          <div className="flex items-center space-x-2">
                            <Phone className="h-3 w-3 text-white/60 flex-shrink-0" />
                            <span className="text-white/80 text-sm">{order.partner.phones.join(', ')}</span>
                          </div>
                        )}
                        {order.partner.emails && order.partner.emails.length > 0 && (
                          <div className="flex items-center space-x-2">
                            <Mail className="h-3 w-3 text-white/60 flex-shrink-0" />
                            <span className="text-white/80 text-sm">{order.partner.emails.join(', ')}</span>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Список товаров */}
                    <div>
                      <h4 className="text-white font-semibold mb-1.5 flex items-center text-sm">
                        <Package className="h-4 w-4 mr-1.5 text-green-400" />
                        Товары ({order.items?.length || 0})
                      </h4>
                      <div className="space-y-1.5">
                        {order.items?.map((item) => (
                          <div key={item.id} className="bg-white/5 rounded p-2 flex items-center justify-between">
                            <div className="flex items-center space-x-2 flex-1 min-w-0">
                              {item.product?.mainImage && (
                                <img
                                  src={item.product.mainImage}
                                  alt={item.product?.name || 'Товар'}
                                  className="w-8 h-8 rounded object-cover flex-shrink-0"
                                />
                              )}
                              <div className="min-w-0 flex-1">
                                <h5 className="text-white font-medium text-sm truncate">{item.product?.name || 'Без названия'}</h5>
                                <p className="text-white/60 text-xs">{item.product?.article || 'Без артикула'}</p>
                                {item.product?.category?.name && (
                                  <Badge
                                    variant="secondary"
                                    className="bg-blue-500/20 text-blue-300 text-xs mt-0.5 px-1.5 py-0.5"
                                  >
                                    {item.product.category.name}
                                  </Badge>
                                )}
                              </div>
                            </div>
                            <div className="text-right flex-shrink-0">
                              <p className="text-white font-semibold text-sm">{item.quantity} шт.</p>
                              <p className="text-white/60 text-xs">{formatCurrency(item.price)}</p>
                              <p className="text-green-400 font-semibold text-sm">{formatCurrency(item.totalPrice)}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </>
                )}
              </div>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
