'use client'

import { useQuery, useMutation } from '@apollo/client'
import {
  Calendar,
  Package,
  CheckCircle,
  Clock,
  XCircle,
  Hash,
  Settings,
  Truck,
} 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 } from '@/graphql/mutations'
import {
  GET_SUPPLY_ORDERS,
  GET_LOGISTICS_PARTNERS,
  GET_MY_SUPPLIES,
  GET_PENDING_SUPPLIES_COUNT,
  GET_WAREHOUSE_PRODUCTS,
} from '@/graphql/queries'
import { GET_MY_EMPLOYEES_V2 } from '@/graphql/queries/employees-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 FulfillmentGoodsOrdersTab() {
  const { user } = useAuthContext()
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set())
  const [selectedEmployee, setSelectedEmployee] = useState<{[orderId: string]: string}>({})
  const [selectedLogistics, setSelectedLogistics] = useState<{[orderId: string]: string}>({})

  // Получаем данные заказов поставок
  const { data, loading, error, refetch } = useQuery(GET_SUPPLY_ORDERS)

  // Получаем сотрудников фулфилмента
  const { data: employeesData } = useQuery(GET_MY_EMPLOYEES_V2)
  
  // Получаем логистических партнеров
  const { data: logisticsData } = useQuery(GET_LOGISTICS_PARTNERS)

  // Мутация для назначения логистики и ответственного
  const [assignLogisticsToSupply, { loading: assigning }] = useMutation(ASSIGN_LOGISTICS_TO_SUPPLY, {
    onCompleted: (data) => {
      if (data.assignLogisticsToSupply.success) {
        toast.success('Товары приняты и логистика назначена!')
        refetch() // Обновляем список заказов
        // Сбрасываем выбранные значения
        setSelectedEmployee({})
        setSelectedLogistics({})
      } else {
        toast.error(data.assignLogisticsToSupply.message || 'Ошибка при назначении логистики')
      }
    },
    refetchQueries: [
      { query: GET_SUPPLY_ORDERS },
      { query: GET_MY_SUPPLIES },
      { query: GET_WAREHOUSE_PRODUCTS },
      { query: GET_PENDING_SUPPLIES_COUNT },
    ],
    onError: (error) => {
      console.error('Error assigning logistics to goods:', error)
      toast.error('Ошибка при назначении логистики')
    },
  })

  const employees = employeesData?.employeesV2?.items || []
  const logisticsPartners = logisticsData?.logisticsPartners || []

  // Получаем данные заказов поставок
  const supplyOrders: SupplyOrder[] = data?.supplyOrders || []

  // Фильтруем заказы для фулфилмента (ТОЛЬКО товары с услугами)
  const fulfillmentOrders = supplyOrders.filter((order) => {
    // Показываем только заказы где текущий фулфилмент-центр является получателем
    const isRecipient = order.fulfillmentCenter?.id === user?.organization?.id
    // НО создатель заказа НЕ мы (т.е. селлер создал заказ для нас)
    const isCreatedByOther = order.organization?.id !== user?.organization?.id
    // И статус не PENDING и не CANCELLED (одобренные поставщиком заявки)
    const isApproved = order.status !== 'CANCELLED' && order.status !== 'PENDING'
    // ✅ КРИТИЧНОЕ ИСПРАВЛЕНИЕ: Показывать только товары (с услугами в рецептуре)
    const isSellerConsumables = order.consumableType === 'SELLER_CONSUMABLES'
    // Проверяем, что это товары (товары содержат услуги в рецептуре)
    const hasServices = order.items?.some(item => item.recipe?.services && item.recipe.services.length > 0)
    const isGoodsOnly = isSellerConsumables && hasServices

    console.warn('🔍 Фильтрация товаров фулфилмента:', {
      orderId: order.id.slice(-8),
      isRecipient,
      isCreatedByOther, 
      isApproved,
      isSellerConsumables,
      hasServices,
      isGoodsOnly,
      consumableType: order.consumableType,
      itemsWithServices: order.items?.filter(item => item.recipe?.services && item.recipe.services.length > 0).length || 0,
      finalResult: isRecipient && isCreatedByOther && isApproved && isGoodsOnly,
    })

    return isRecipient && isCreatedByOther && isApproved && isGoodsOnly
  })

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

  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: 'Логистика готова',
        color: 'bg-blue-500/20 text-blue-300 border-blue-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-purple-500/20 text-purple-300 border-purple-500/30',
        icon: Truck,
      },
      DELIVERED: {
        label: 'Доставлено',
        color: 'bg-green-500/20 text-green-300 border-green-500/30',
        icon: CheckCircle,
      },
      CANCELLED: {
        label: 'Отменено',
        color: 'bg-red-500/20 text-red-300 border-red-500/30',
        icon: XCircle,
      },
    }

    const config = statusMap[status as keyof typeof statusMap]
    if (!config) {
      return (
        <Badge className="bg-gray-500/20 text-gray-300 border-gray-500/30 border flex items-center gap-1 text-xs">
          <Clock className="h-3 w-3" />
          {status}
        </Badge>
      )
    }

    const { label, color, icon: Icon } = config
    return (
      <Badge className={`${color} border flex items-center gap-1 text-xs`}>
        <Icon className="h-3 w-3" />
        {label}
      </Badge>
    )
  }

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

  const handleAcceptOrder = async (orderId: string) => {
    const employee = selectedEmployee[orderId]
    const logistics = selectedLogistics[orderId]
    
    if (!employee) {
      toast.error('Выберите ответственного сотрудника')
      return
    }
    
    if (!logistics) {
      toast.error('Выберите логистического партнера')
      return
    }
    
    console.warn('🎯 Принятие заказа товаров:', {
      orderId,
      employee,
      logistics,
    })
    
    try {
      await assignLogisticsToSupply({
        variables: {
          supplyOrderId: orderId,
          logisticsPartnerId: logistics,
          responsibleId: employee,
        },
      })
    } catch (error) {
      console.error('Error accepting goods order:', error)
    }
  }

  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 h-64">
        <div className="text-white">Загрузка товаров...</div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-300">Ошибка загрузки: {error.message}</div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {ordersWithNumbers.length === 0 ? (
        <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
          <div className="text-center">
            <Package className="h-12 w-12 text-white/40 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">Нет новых поставок товаров</h3>
            <p className="text-white/60">
              Поставки товаров от селлеров будут отображаться здесь после одобрения поставщиками
            </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 cursor-pointer"
            onClick={() => toggleOrderExpansion(order.id)}
          >
            {/* Основная информация о заказе */}
            <div className="p-4">
              <div className="flex items-center justify-between">
                {/* Левая часть */}
                <div className="flex items-center space-x-4 flex-1 min-w-0">
                  {/* Номер заказа */}
                  <div className="flex items-center space-x-2">
                    <Hash className="h-4 w-4 text-white/60" />
                    <span className="text-white font-semibold">#{order.number}</span>
                    <span className="text-white/60 text-xs">({order.id.slice(-8)})</span>
                  </div>

                  {/* Информация о поставщике */}
                  <div className="flex items-center space-x-3 min-w-0">
                    <div className="flex items-center space-x-2">
                      <Avatar className="w-8 h-8">
                        <AvatarFallback className="bg-blue-500 text-white text-sm">
                          {getInitials(order.partner.name || order.partner.fullName || 'П')}
                        </AvatarFallback>
                      </Avatar>
                    </div>
                    <div className="min-w-0">
                      <h3 className="text-white font-medium text-sm truncate">
                        {order.partner.name || order.partner.fullName}
                      </h3>
                      <p className="text-white/60 text-xs">Поставщик товаров</p>
                    </div>
                  </div>

                  {/* Краткая информация */}
                  <div className="hidden lg:flex items-center space-x-4">
                    <div className="flex items-center space-x-1">
                      <Calendar className="h-4 w-4 text-blue-400" />
                      <span className="text-white text-sm">{formatDate(order.deliveryDate)}</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Package className="h-4 w-4 text-green-400" />
                      <span className="text-white text-sm">{order.totalItems} поз.</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Settings className="h-4 w-4 text-purple-400" />
                      <span className="text-white text-sm">
                        {order.items?.filter(item => item.recipe?.services && item.recipe.services.length > 0).length || 0} услуг
                      </span>
                    </div>
                  </div>
                </div>

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

                  {/* Кнопка принятия для товаров */}
                  {order.status === 'SUPPLIER_APPROVED' && (
                    <div className="flex items-center space-x-2">
                      <Button
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleAcceptOrder(order.id)
                        }}
                        className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30 text-xs px-3 py-1 h-7"
                        disabled={!selectedEmployee[order.id] || !selectedLogistics[order.id] || assigning}
                      >
                        <CheckCircle className="h-3 w-3 mr-1" />
                        Принять
                      </Button>
                    </div>
                  )}
                </div>
              </div>

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

                  {/* Форма выбора сотрудника и логистики для SUPPLIER_APPROVED */}
                  {order.status === 'SUPPLIER_APPROVED' && (
                    <div className="mb-4 p-4 bg-white/5 rounded-lg">
                      <h4 className="text-white font-semibold mb-3">Параметры приемки товаров</h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {/* Выбор ответственного сотрудника */}
                        <div>
                          <label className="block text-white/80 text-sm mb-2">
                            Ответственный сотрудник *
                          </label>
                          <select
                            value={selectedEmployee[order.id] || ''}
                            onChange={(e) => setSelectedEmployee({...selectedEmployee, [order.id]: e.target.value})}
                            className="w-full bg-white/10 border border-white/20 rounded-md px-3 py-2 text-white text-sm focus:outline-none focus:ring-1 focus:ring-green-500 focus:border-transparent"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <option value="">Выберите сотрудника</option>
                            {employees.map((employee: any) => (
                              <option key={employee.id} value={employee.id} className="bg-gray-800">
                                {employee.personalInfo.fullName}
                              </option>
                            ))}
                          </select>
                        </div>

                        {/* Выбор логистического партнера */}
                        <div>
                          <label className="block text-white/80 text-sm mb-2">
                            Логистический партнер *
                          </label>
                          <select
                            value={selectedLogistics[order.id] || ''}
                            onChange={(e) => setSelectedLogistics({...selectedLogistics, [order.id]: e.target.value})}
                            className="w-full bg-white/10 border border-white/20 rounded-md px-3 py-2 text-white text-sm focus:outline-none focus:ring-1 focus:ring-green-500 focus:border-transparent"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <option value="">Выберите логистику</option>
                            {logisticsPartners.map((partner: { id: string; name?: string; fullName?: string }) => (
                              <option key={partner.id} value={partner.id} className="bg-gray-800">
                                {partner.name || partner.fullName}
                              </option>
                            ))}
                          </select>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Общая информация о заказе */}
                  <div className="mb-4 p-3 bg-white/5 rounded">
                    <div className="flex items-center justify-between">
                      <span className="text-white/60">Общая сумма заказа:</span>
                      <span className="text-white font-semibold text-lg">
                        {formatCurrency(order.totalAmount)}
                      </span>
                    </div>
                  </div>

                  {/* Список товаров с услугами */}
                  <div>
                    <h4 className="text-white font-semibold mb-3 flex items-center text-sm">
                      <Package className="h-4 w-4 mr-2 text-green-400" />
                      Товары к обработке ({order.items.length})
                    </h4>
                    <div className="space-y-3">
                      {order.items.map((item) => (
                        <div key={item.id} className="bg-white/5 rounded p-3">
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex-1 min-w-0">
                              <h5 className="text-white font-medium text-sm">{item.product.name}</h5>
                              <p className="text-white/60 text-xs">Артикул: {item.product.article}</p>
                              {item.product.category && (
                                <Badge variant="secondary" className="bg-blue-500/20 text-blue-300 text-xs mt-1">
                                  {item.product.category.name}
                                </Badge>
                              )}
                            </div>
                            <div className="text-right flex-shrink-0 ml-4">
                              <p className="text-white font-semibold">{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>

                          {/* Отображение услуг если есть */}
                          {item.recipe?.services && item.recipe.services.length > 0 && (
                            <div className="mt-2 p-2 bg-purple-500/10 rounded border border-purple-500/20">
                              <p className="text-purple-300 text-xs font-medium mb-1">
                                Услуги фулфилмента ({item.recipe.services.length}):
                              </p>
                              <div className="text-purple-200 text-xs">
                                {item.recipe.services.map(service => service.name).join(', ')}
                              </div>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              )}
            </div>
          </Card>
        ))
      )}
    </div>
  )
}