'use client'

import { useQuery, useMutation } from '@apollo/client'
import {
  ChevronRight,
  ChevronDown,
  CheckCircle,
  XCircle,
  Truck,
  Calendar,
  User,
  DollarSign,
  Wrench,
  Package2,
  Clock,
  TrendingUp,
  TrendingDown,
  Search,
  Store,
  ArrowUpDown,
} from 'lucide-react'
import React, { useState } from 'react'
import { toast } from 'sonner'

import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
  UPDATE_SUPPLY_ORDER_STATUS,
  SUPPLIER_APPROVE_ORDER,
  SUPPLIER_REJECT_ORDER,
  SUPPLIER_SHIP_ORDER,
} from '@/graphql/mutations'
import { GET_SUPPLY_ORDERS } from '@/graphql/queries'
import { useAuthContext } from '@/contexts/AuthContext'
import { useRealtime } from '@/hooks/useRealtime'

// Типы для данных заказов
interface SupplyOrderItem {
  id: string
  quantity: number
  price: number
  totalPrice: number
  product: {
    id: string
    name: string
    article: string
    category?: {
      id: string
      name: string
    }
  }
}

interface SupplyOrder {
  id: string
  status: string
  totalAmount: number
  totalItems: number
  deliveryDate: string
  createdAt: string
  partner: {
    id: string
    name?: string
    fullName?: string
    phones?: string[]
    emails?: string[]
  }
  organization: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  fulfillmentCenter?: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  items: SupplyOrderItem[]
}

// Компонент для заголовка таблицы
const TableHeader = ({
  children,
  field,
  sortable = false,
  sortField,
  sortOrder,
  onSort,
}: {
  children: React.ReactNode
  field: string
  sortable?: boolean
  sortField?: string
  sortOrder?: 'asc' | 'desc'
  onSort?: (field: string) => void
}) => (
  <div
    className={`px-3 py-2 text-xs font-bold text-white flex items-center justify-between ${
      sortable ? 'cursor-pointer hover:bg-white/5' : ''
    }`}
    onClick={() => sortable && onSort && onSort(field)}
  >
    <span>{children}</span>
    {sortable && <ArrowUpDown className={`h-3 w-3 ml-1 ${sortField === field ? 'text-blue-400' : 'text-white/40'}`} />}
  </div>
)

// Компонент для статистических карточек
const StatsCard = ({
  title,
  value,
  change = 0,
  icon: Icon,
  iconColor = 'text-blue-400',
  iconBg = 'bg-blue-500/20',
  subtitle,
}: {
  title: string
  value: string | number
  change?: number
  icon: React.ComponentType<any>
  iconColor?: string
  iconBg?: string
  subtitle?: string
}) => (
  <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
    <div className="flex items-center justify-between">
      <div className="flex items-center space-x-3">
        <div className={`p-2 rounded-lg ${iconBg}`}>
          <Icon className={`h-5 w-5 ${iconColor}`} />
        </div>
        <div>
          <p className="text-white/60 text-sm">{title}</p>
          <div className="flex items-center space-x-2">
            <p className="text-white text-xl font-bold">{value}</p>
            {change !== 0 && (
              <div className="flex items-center space-x-1">
                {change > 0 ? (
                  <TrendingUp className="h-3 w-3 text-green-400" />
                ) : (
                  <TrendingDown className="h-3 w-3 text-red-400" />
                )}
                <span className={`text-xs font-medium ${change > 0 ? 'text-green-400' : 'text-red-400'}`}>
                  {Math.abs(change)}%
                </span>
              </div>
            )}
          </div>
          {subtitle && <p className="text-white/40 text-xs mt-1">{subtitle}</p>}
        </div>
      </div>
    </div>
  </Card>
)

export function RealSupplyOrdersTab() {
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set())
  const [searchTerm, setSearchTerm] = useState('')
  const [sortField, setSortField] = useState<string>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  const { user } = useAuthContext()

  const { data, loading, error, refetch } = useQuery(GET_SUPPLY_ORDERS, {
    fetchPolicy: 'cache-and-network',
    notifyOnNetworkStatusChange: true,
  })

  // Realtime: обновление списка заказов
  useRealtime({
    onEvent: (evt) => {
      if (evt.type === 'supply-order:new' || evt.type === 'supply-order:updated') {
        refetch()
      }
    },
  })

  // Мутация для обновления статуса заказа
  const [updateSupplyOrderStatus, { loading: updating }] = useMutation(UPDATE_SUPPLY_ORDER_STATUS, {
    onCompleted: (data) => {
      if (data.updateSupplyOrderStatus.success) {
        toast.success(data.updateSupplyOrderStatus.message)
      } else {
        toast.error(data.updateSupplyOrderStatus.message)
      }
    },
    onError: (error) => {
      console.error('Error updating supply order status:', error)
      toast.error('Ошибка при обновлении статуса заказа')
    },
    update: (cache, { data }) => {
      if (data?.updateSupplyOrderStatus?.success && data?.updateSupplyOrderStatus?.order) {
        console.warn(
          `✅ Обновляем кэш для заказа ${data.updateSupplyOrderStatus.order.id} на статус ${data.updateSupplyOrderStatus.order.status}`,
        )

        // Точечно обновляем кэш для конкретного заказа
        cache.modify({
          id: cache.identify(data.updateSupplyOrderStatus.order),
          fields: {
            status() {
              console.warn(`📝 Обновляем поле status для заказа ${data.updateSupplyOrderStatus.order.id}`)
              return data.updateSupplyOrderStatus.order.status
            },
          },
        })

        // Также обновляем данные в запросе GET_SUPPLY_ORDERS если нужно
        try {
          const existingData = cache.readQuery({
            query: GET_SUPPLY_ORDERS,
          }) as any
          if (existingData?.supplyOrders) {
            console.warn(`📋 Обновляем список заказов в кэше, всего заказов: ${existingData.supplyOrders.length}`)
            cache.writeQuery({
              query: GET_SUPPLY_ORDERS,
              data: {
                ...existingData,
                supplyOrders: existingData.supplyOrders.map((order: any) => {
                  if (order.id === data.updateSupplyOrderStatus.order.id) {
                    console.warn(`🎯 Найден и обновлен заказ ${order.id}`)
                    return {
                      ...order,
                      status: data.updateSupplyOrderStatus.order.status,
                    }
                  }
                  return order
                }),
              },
            })
          }
        } catch (error) {
          console.warn('Cache update fallback - data not in cache yet', error)
        }
      }
    },
  })

  // Мутации для поставщика
  const [supplierApproveOrder] = useMutation(SUPPLIER_APPROVE_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    awaitRefetchQueries: true,
    onCompleted: (data) => {
      if (data.supplierApproveOrder.success) {
        toast.success(data.supplierApproveOrder.message)
      } else {
        toast.error(data.supplierApproveOrder.message)
      }
    },
    onError: (error) => {
      console.error('Error approving order:', error)
      toast.error('Ошибка при одобрении заказа')
    },
  })

  const [supplierRejectOrder] = useMutation(SUPPLIER_REJECT_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    onCompleted: (data) => {
      if (data.supplierRejectOrder.success) {
        toast.success(data.supplierRejectOrder.message)
      } else {
        toast.error(data.supplierRejectOrder.message)
      }
    },
    onError: (error) => {
      console.error('Error rejecting order:', error)
      toast.error('Ошибка при отклонении заказа')
    },
  })

  const [supplierShipOrder] = useMutation(SUPPLIER_SHIP_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    onCompleted: (data) => {
      if (data.supplierShipOrder.success) {
        toast.success(data.supplierShipOrder.message)
      } else {
        toast.error(data.supplierShipOrder.message)
      }
    },
    onError: (error) => {
      console.error('Error shipping order:', error)
      toast.error('Ошибка при отправке заказа')
    },
  })

  // Получаем ID текущей организации (поставщика)
  const currentOrganizationId = user?.organization?.id

  // Фильтруем заказы где текущая организация является поставщиком
  const incomingSupplyOrders: SupplyOrder[] = (data?.supplyOrders || []).filter((order: SupplyOrder) => {
    return order.partner.id === currentOrganizationId
  })

  // Отладочное логирование для проверки дублирующихся ID
  React.useEffect(() => {
    if (incomingSupplyOrders.length > 0) {
      const ids = incomingSupplyOrders.map((order) => order.id)
      const uniqueIds = new Set(ids)
      if (ids.length !== uniqueIds.size) {
        console.warn(`⚠️ Обнаружены дублирующиеся ID заказов! Всего: ${ids.length}, уникальных: ${uniqueIds.size}`)
        console.warn(
          'Дублирующиеся ID:',
          ids.filter((id, index) => ids.indexOf(id) !== index),
        )
      } else {
        console.warn(`✅ Все ID заказов уникальны: ${ids.length} заказов`)
      }
    }
  }, [incomingSupplyOrders])

  // Функции для работы с таблицей
  const toggleOrderExpansion = (orderId: string) => {
    const newExpanded = new Set(expandedOrders)
    if (newExpanded.has(orderId)) {
      newExpanded.delete(orderId)
    } else {
      newExpanded.add(orderId)
    }
    setExpandedOrders(newExpanded)
  }

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortOrder('asc')
    }
  }

  const handleStatusUpdate = async (orderId: string, status: string) => {
    console.warn(`🔄 Обновляем статус заказа ${orderId} на ${status}`)

    try {
      await updateSupplyOrderStatus({
        variables: {
          id: orderId,
          status,
        },
      })
    } catch (error) {
      console.error('Error updating order status:', error)
    }
  }

  // Фильтрация и сортировка заказов
  const filteredAndSortedOrders = incomingSupplyOrders
    .filter((order) => {
      const searchLower = searchTerm.toLowerCase()
      return (
        order.id.toLowerCase().includes(searchLower) ||
        (order.organization.name || order.organization.fullName || '').toLowerCase().includes(searchLower) ||
        order.items.some(
          (item) =>
            item.product.name.toLowerCase().includes(searchLower) ||
            item.product.article.toLowerCase().includes(searchLower),
        )
      )
    })
    .sort((a, b) => {
      let aValue, bValue

      switch (sortField) {
        case 'organization':
          aValue = a.organization.name || a.organization.fullName || ''
          bValue = b.organization.name || b.organization.fullName || ''
          break
        case 'totalAmount':
          aValue = a.totalAmount
          bValue = b.totalAmount
          break
        case 'totalItems':
          aValue = a.totalItems
          bValue = b.totalItems
          break
        case 'deliveryDate':
          aValue = new Date(a.deliveryDate).getTime()
          bValue = new Date(b.deliveryDate).getTime()
          break
        case 'status':
          aValue = a.status
          bValue = b.status
          break
        default:
          aValue = new Date(a.createdAt).getTime()
          bValue = new Date(b.createdAt).getTime()
      }

      if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1
      if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1
      return 0
    })

  // Функции форматирования
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount)
  }

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

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

  const formatNumber = (num: number) => {
    return new Intl.NumberFormat('ru-RU').format(num)
  }

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      PENDING: {
        label: 'Ожидает одобрения',
        className: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30',
      },
      SUPPLIER_APPROVED: {
        label: 'Ожидает подтверждения логистики',
        className: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      },
      LOGISTICS_CONFIRMED: {
        label: 'Готово к отправке',
        className: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
      },
      SHIPPED: {
        label: 'В пути',
        className: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      },
      DELIVERED: {
        label: 'Доставлено',
        className: 'bg-green-500/20 text-green-300 border-green-500/30',
      },
      CANCELLED: {
        label: 'Отменено',
        className: 'bg-red-500/20 text-red-300 border-red-500/30',
      },
      // Устаревшие статусы для обратной совместимости
      CONFIRMED: {
        label: 'Одобрено (устаревший)',
        className: 'bg-green-500/20 text-green-300 border-green-500/30',
      },
      IN_TRANSIT: {
        label: 'В пути (устаревший)',
        className: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      },
    }

    const config = statusConfig[status as keyof typeof statusConfig] || {
      label: status,
      className: 'bg-gray-500/20 text-gray-300 border-gray-500/30',
    }

    return <Badge className={`${config.className} border text-xs`}>{config.label}</Badge>
  }

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

  const getColorForOrder = (orderId: string): string => {
    const colors = [
      'bg-blue-500',
      'bg-green-500',
      'bg-purple-500',
      'bg-orange-500',
      'bg-pink-500',
      'bg-indigo-500',
      'bg-teal-500',
      'bg-red-500',
    ]
    const hash = orderId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
    return colors[hash % colors.length]
  }

  // Цветовые схемы для заказов
  const getColorScheme = (orderId: string) => {
    const colorSchemes = [
      {
        bg: 'bg-blue-500/5',
        border: 'border-blue-500/30',
        borderLeft: 'border-l-blue-400',
        text: 'text-blue-100',
        indicator: 'bg-blue-400 border-blue-300',
        hover: 'hover:bg-blue-500/10',
        header: 'bg-blue-500/20 border-blue-500/40',
      },
      {
        bg: 'bg-pink-500/5',
        border: 'border-pink-500/30',
        borderLeft: 'border-l-pink-400',
        text: 'text-pink-100',
        indicator: 'bg-pink-400 border-pink-300',
        hover: 'hover:bg-pink-500/10',
        header: 'bg-pink-500/20 border-pink-500/40',
      },
      {
        bg: 'bg-emerald-500/5',
        border: 'border-emerald-500/30',
        borderLeft: 'border-l-emerald-400',
        text: 'text-emerald-100',
        indicator: 'bg-emerald-400 border-emerald-300',
        hover: 'hover:bg-emerald-500/10',
        header: 'bg-emerald-500/20 border-emerald-500/40',
      },
      {
        bg: 'bg-orange-500/5',
        border: 'border-orange-500/30',
        borderLeft: 'border-l-orange-400',
        text: 'text-orange-100',
        indicator: 'bg-orange-400 border-orange-300',
        hover: 'hover:bg-orange-500/10',
        header: 'bg-orange-500/20 border-orange-500/40',
      },
    ]

    const hash = orderId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
    return colorSchemes[hash % colorSchemes.length]
  }

  // Подсчет статистики
  const totalOrders = incomingSupplyOrders.length
  const totalAmount = incomingSupplyOrders.reduce((sum, order) => sum + order.totalAmount, 0)
  const totalItems = incomingSupplyOrders.reduce((sum, order) => sum + order.totalItems, 0)
  const pendingOrders = incomingSupplyOrders.filter((order) => order.status === 'PENDING').length
  const approvedOrders = incomingSupplyOrders.filter(
    (order) =>
      order.status === 'SUPPLIER_APPROVED' || order.status === 'LOGISTICS_CONFIRMED' || order.status === 'CONFIRMED',
  ).length
  const inTransitOrders = incomingSupplyOrders.filter(
    (order) => order.status === 'SHIPPED' || order.status === 'IN_TRANSIT',
  ).length

  // Подсчет общих итогов для отображения в строке итогов
  const totals = {
    orders: filteredAndSortedOrders.length,
    amount: filteredAndSortedOrders.reduce((sum, order) => sum + order.totalAmount, 0),
    items: filteredAndSortedOrders.reduce((sum, order) => sum + order.totalItems, 0),
    pending: filteredAndSortedOrders.filter((order) => order.status === 'PENDING').length,
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
        <span className="ml-3 text-white/60">Загрузка заявок...</span>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <Wrench className="h-12 w-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400 font-medium">Ошибка загрузки заявок</p>
          <p className="text-white/60 text-sm mt-2">{error.message}</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col overflow-hidden">
      {/* Статистические карточки - 30% экрана */}
      <div className="flex-shrink-0 mb-4" style={{ maxHeight: '30vh' }}>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          <StatsCard
            title="Всего заявок"
            value={totalOrders}
            icon={Package2}
            iconColor="text-orange-400"
            iconBg="bg-orange-500/20"
            subtitle="Заявки от селлеров"
          />
          <StatsCard
            title="Ожидают одобрения"
            value={pendingOrders}
            icon={Clock}
            iconColor="text-blue-400"
            iconBg="bg-blue-500/20"
            subtitle="Требуют решения"
          />
          <StatsCard
            title="Одобрено"
            value={approvedOrders}
            icon={CheckCircle}
            iconColor="text-green-400"
            iconBg="bg-green-500/20"
            subtitle="Готовы к отправке"
          />
          <StatsCard
            title="В пути"
            value={inTransitOrders}
            icon={Truck}
            iconColor="text-yellow-400"
            iconBg="bg-yellow-500/20"
            subtitle="Доставляются"
          />
          <StatsCard
            title="Общая сумма"
            value={formatCurrency(totalAmount)}
            icon={TrendingUp}
            iconColor="text-green-400"
            iconBg="bg-green-500/20"
            subtitle="Стоимость заявок"
          />
          <StatsCard
            title="Всего единиц"
            value={totalItems}
            icon={Wrench}
            iconColor="text-purple-400"
            iconBg="bg-purple-500/20"
            subtitle="Количество товаров"
          />
        </div>
      </div>

      {/* Основная таблица - 70% экрана */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <Card className="bg-white/10 backdrop-blur border-white/20 flex-1 flex flex-col overflow-hidden">
          {/* Шапка таблицы с поиском */}
          <div className="p-4 border-b border-white/10 flex-shrink-0">
            <div className="flex items-center justify-between">
              <h2 className="text-base font-semibold text-white flex items-center space-x-2">
                <Store className="h-4 w-4 text-blue-400" />
                <span>Заявки на расходники</span>
              </h2>

              {/* Поиск */}
              <div className="relative mx-2.5 flex-1 max-w-xs">
                <Search className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-white/40" />
                <Input
                  placeholder="Поиск по заявкам..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-8 h-8 text-sm glass-input text-white placeholder:text-white/40"
                />
              </div>

              <Badge variant="secondary" className="bg-blue-500/20 text-blue-300 text-xs">
                {filteredAndSortedOrders.length} заявок
              </Badge>
            </div>
          </div>

          {/* Заголовки таблицы */}
          <div className="flex-shrink-0 bg-blue-500/20 border-b border-blue-500/40">
            <div className="grid grid-cols-7 gap-0">
              <TableHeader field="id" sortable sortField={sortField} sortOrder={sortOrder} onSort={handleSort}>
                № / ID
              </TableHeader>
              <TableHeader
                field="organization"
                sortable
                sortField={sortField}
                sortOrder={sortOrder}
                onSort={handleSort}
              >
                Заказчик
              </TableHeader>
              <TableHeader
                field="deliveryDate"
                sortable
                sortField={sortField}
                sortOrder={sortOrder}
                onSort={handleSort}
              >
                Дата поставки
              </TableHeader>
              <TableHeader field="totalItems" sortable sortField={sortField} sortOrder={sortOrder} onSort={handleSort}>
                Количество
              </TableHeader>
              <TableHeader field="totalAmount" sortable sortField={sortField} sortOrder={sortOrder} onSort={handleSort}>
                Сумма
              </TableHeader>
              <TableHeader field="status" sortable sortField={sortField} sortOrder={sortOrder} onSort={handleSort}>
                Статус
              </TableHeader>
              <TableHeader field="actions">Действия</TableHeader>
            </div>
          </div>

          {/* Строка с итогами */}
          <div className="flex-shrink-0 bg-blue-500/25 border-b border-blue-500/50">
            <div className="grid grid-cols-7 gap-0">
              <div className="px-3 py-2 text-xs font-bold text-blue-300">ИТОГО ({totals.orders})</div>
              <div className="px-3 py-2 text-xs font-bold text-white">{totals.orders} заказчиков</div>
              <div className="px-3 py-2 text-xs font-bold text-white">-</div>
              <div className="px-3 py-2 text-xs font-bold text-white">{formatNumber(totals.items)} шт</div>
              <div className="px-3 py-2 text-xs font-bold text-white">{formatCurrency(totals.amount)}</div>
              <div className="px-3 py-2 text-xs font-bold text-white">{totals.pending} ожидают</div>
              <div className="px-3 py-2 text-xs font-bold text-white">-</div>
            </div>
          </div>

          {/* Скроллируемый контент таблицы */}
          <div className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent">
            {filteredAndSortedOrders.length === 0 ? (
              <div className="flex items-center justify-center h-full">
                <div className="text-center">
                  <Wrench className="h-12 w-12 text-white/40 mx-auto mb-4" />
                  <p className="text-white/60 font-medium">
                    {incomingSupplyOrders.length === 0 ? 'Нет заявок на расходники' : 'Заявки не найдены'}
                  </p>
                  <p className="text-white/40 text-sm mt-2">
                    {incomingSupplyOrders.length === 0
                      ? 'Здесь будут отображаться заявки от селлеров'
                      : searchTerm
                        ? 'Попробуйте изменить поисковый запрос'
                        : 'Данные о заявках будут отображены здесь'}
                  </p>
                </div>
              </div>
            ) : (
              filteredAndSortedOrders.map((order, index) => {
                const colorScheme = getColorScheme(order.id)
                const isOrderExpanded = expandedOrders.has(order.id)
                const organizationName = order.organization.name || order.organization.fullName || 'Заказчик'

                return (
                  <div
                    key={order.id}
                    className={`border-b ${colorScheme.border} ${colorScheme.hover} transition-colors border-l-8 ${colorScheme.borderLeft} ${colorScheme.bg} shadow-sm hover:shadow-md`}
                  >
                    {/* Основная строка заказа */}
                    <div className="grid grid-cols-7 gap-0">
                      <div className="px-3 py-2.5 flex items-center space-x-2">
                        <span className="text-white/60 text-xs">{filteredAndSortedOrders.length - index}</span>
                        <button
                          onClick={() => toggleOrderExpansion(order.id)}
                          className="text-white/60 hover:text-white"
                        >
                          {isOrderExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
                        </button>
                        <span className="text-white font-medium text-xs">{order.id.slice(-8)}</span>
                      </div>

                      <div className="px-3 py-2.5 flex items-center space-x-2">
                        <Avatar className="w-6 h-6">
                          <AvatarFallback className={`${getColorForOrder(order.id)} text-white text-xs`}>
                            {getInitials(organizationName)}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <span className="text-white font-medium text-sm">{organizationName}</span>
                          <p className="text-white/60 text-xs">{order.organization.type}</p>
                        </div>
                      </div>

                      <div className="px-3 py-2.5 flex items-center space-x-2">
                        <Calendar className="h-4 w-4 text-white/40" />
                        <span className="text-white font-semibold text-sm">{formatDate(order.deliveryDate)}</span>
                      </div>

                      <div className="px-3 py-2.5">
                        <span className="text-white font-semibold text-sm">{order.totalItems} шт</span>
                      </div>

                      <div className="px-3 py-2.5 flex items-center space-x-2">
                        <DollarSign className="h-4 w-4 text-white/40" />
                        <span className="text-green-400 font-bold text-sm">{formatCurrency(order.totalAmount)}</span>
                      </div>

                      <div className="px-3 py-2.5">{getStatusBadge(order.status)}</div>

                      <div className="px-3 py-2.5">
                        <div className="flex items-center space-x-1">
                          {/* Кнопки для поставщика */}
                          {console.warn(
                            `DEBUG: Заказ ${order.id.slice(-8)} - статус: ${order.status}, partnerId: ${order.partner?.id}, currentOrganizationId: ${currentOrganizationId}, показать кнопки: ${order.status === 'PENDING' && order.partner?.id === currentOrganizationId}`,
                          )}
                          {order.status === 'PENDING' && order.partner?.id === currentOrganizationId && (
                            <div className="flex items-center space-x-2">
                              <Button
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation()
                                  supplierApproveOrder({ variables: { id: order.id } })
                                }}
                                disabled={updating}
                                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"
                              >
                                <CheckCircle className="h-3 w-3 mr-1" />
                                Одобрить
                              </Button>
                              <Button
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation()
                                  supplierRejectOrder({ variables: { id: order.id } })
                                }}
                                disabled={updating}
                                className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30 text-xs px-2 py-1 h-6"
                              >
                                <XCircle className="h-3 w-3 mr-1" />
                                Отклонить
                              </Button>
                            </div>
                          )}
                          {order.status === 'SUPPLIER_APPROVED' && (
                            <div className="text-blue-300 text-xs">Ожидает подтверждения логистики</div>
                          )}
                          {order.status === 'LOGISTICS_CONFIRMED' && order.partner?.id === currentOrganizationId && (
                            <Button
                              size="sm"
                              onClick={(e) => {
                                e.stopPropagation()
                                supplierShipOrder({ variables: { id: order.id } })
                              }}
                              disabled={updating}
                              className="bg-orange-500/20 hover:bg-orange-500/30 text-orange-300 border border-orange-500/30 text-xs px-2 py-1 h-6"
                            >
                              <Truck className="h-3 w-3 mr-1" />
                              Отправить
                            </Button>
                          )}
                          {order.status === 'SHIPPED' && (
                            <div className="text-orange-300 text-xs">В пути - ожидает получения</div>
                          )}
                          {order.status === 'DELIVERED' && <div className="text-green-300 text-xs">Получено</div>}
                          {false && ( // Временно отключаем старую кнопку
                            <>
                              <Button
                                size="sm"
                                onClick={() => handleStatusUpdate(order.id, 'CONFIRMED')}
                                disabled={updating}
                                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"
                              >
                                <CheckCircle className="h-3 w-3 mr-1" />
                                Одобрить
                              </Button>
                              <Button
                                size="sm"
                                onClick={() => handleStatusUpdate(order.id, 'CANCELLED')}
                                disabled={updating}
                                className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30 text-xs px-2 py-1 h-6"
                              >
                                <XCircle className="h-3 w-3 mr-1" />
                                Отклонить
                              </Button>
                            </>
                          )}
                          {order.status === 'CONFIRMED' && (
                            <Button
                              size="sm"
                              onClick={() => handleStatusUpdate(order.id, 'IN_TRANSIT')}
                              disabled={updating}
                              className="bg-yellow-500/20 hover:bg-yellow-500/30 text-yellow-300 border border-yellow-500/30 text-xs px-2 py-1 h-6"
                            >
                              <Truck className="h-3 w-3 mr-1" />
                              Отправить
                            </Button>
                          )}
                          {order.status === 'CANCELLED' && <span className="text-red-400 text-xs">Отклонена</span>}
                          {order.status === 'IN_TRANSIT' && <span className="text-yellow-400 text-xs">В пути</span>}
                          {order.status === 'DELIVERED' && <span className="text-green-400 text-xs">Доставлена</span>}
                        </div>
                      </div>
                    </div>

                    {/* Развернутая информация о заказе */}
                    {isOrderExpanded && (
                      <div className={`${colorScheme.bg} border-t ${colorScheme.border}`}>
                        <div className="p-6">
                          <div className="flex items-center justify-between mb-4">
                            <h4 className="text-white font-semibold">Состав заявки:</h4>
                            <div className="flex items-center space-x-2 text-white/60 text-sm">
                              <Calendar className="h-4 w-4" />
                              <span>Дата создания: {formatDateTime(order.createdAt)}</span>
                            </div>
                          </div>
                          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {order.items.map((item) => (
                              <Card key={item.id} className="bg-white/10 backdrop-blur border-white/20 p-4">
                                <div className="space-y-3">
                                  <div>
                                    <h5 className="text-white font-medium mb-1">{item.product.name}</h5>
                                    <p className="text-white/60 text-sm">Артикул: {item.product.article}</p>
                                    {item.product.category && (
                                      <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-xs mt-2">
                                        {item.product.category.name}
                                      </Badge>
                                    )}
                                  </div>
                                  <div className="flex items-center justify-between">
                                    <div className="text-sm">
                                      <p className="text-white/60">Количество: {item.quantity} шт</p>
                                      <p className="text-white/60">Цена: {formatCurrency(item.price)}</p>
                                    </div>
                                    <div className="text-right">
                                      <p className="text-green-400 font-semibold">{formatCurrency(item.totalPrice)}</p>
                                    </div>
                                  </div>
                                </div>
                              </Card>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                )
              })
            )}
          </div>
        </Card>
      </div>
    </div>
  )
}
