'use client'

import { useQuery, useMutation } from '@apollo/client'
import { Clock, CheckCircle, Truck, Package } from 'lucide-react'
import { useState, useMemo, useCallback } from 'react'
import { toast } from 'sonner'

import { MultiLevelSuppliesTable } from '@/components/supplies/multilevel-supplies-table'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
// V2 система - прямое использование V2 данных
import { SUPPLIER_APPROVE_CONSUMABLE_SUPPLY, SUPPLIER_REJECT_CONSUMABLE_SUPPLY, SUPPLIER_SHIP_CONSUMABLE_SUPPLY } from '@/graphql/mutations/fulfillment-consumables-v2'
import { UPDATE_SELLER_GOODS_SUPPLY_STATUS, UPDATE_SUPPLY_VOLUME_V2, UPDATE_SUPPLY_PACKAGES_V2, GET_MY_SELLER_GOODS_SUPPLY_REQUESTS } from '@/graphql/mutations/seller-goods-v2'
import { GET_MY_SUPPLIER_CONSUMABLE_SUPPLIES } from '@/graphql/queries/fulfillment-consumables-v2'
import { UPDATE_SELLER_SUPPLY_STATUS, GET_MY_SELLER_SUPPLY_REQUESTS } from '@/graphql/queries/seller-consumables-v2'
import { useAuthContext } from '@/contexts/AuthContext'

import { SupplierOrderStats } from './supplier-order-stats'
import { SupplierOrdersSearch } from './supplier-orders-search'

// V2 типы данных (адаптер под SupplyOrder для совместимости с UI)
interface Product {
  id: string
  name: string
  article: string
  description?: string
  category?: {
    id: string
    name: string
  }
}

interface SupplyOrderItem {
  id: string
  productId: string
  quantity: number
  price: number
  totalPrice: number
  product: Product
}

interface Organization {
  id: string
  name?: string
  fullName?: string
  inn?: string
  type?: string
}

interface SupplyOrder {
  id: string
  organizationId: string
  partnerId: string
  deliveryDate: string
  status: string
  totalAmount: number
  totalItems: number
  fulfillmentCenterId?: string
  logisticsPartnerId?: string
  packagesCount?: number
  volume?: number
  responsibleEmployee?: string
  notes?: string
  createdAt: string
  updatedAt: string
  partner: Organization
  organization: Organization
  fulfillmentCenter?: Organization
  logisticsPartner?: Organization
  routes: never[]
  items: SupplyOrderItem[]
}

export function SupplierOrdersTabsV2() {
  const { user: _user } = useAuthContext()
  const [activeTab, setActiveTab] = useState('new')
  const [searchQuery, setSearchQuery] = useState('')
  const [sortField, setSortField] = useState<string>('createdAt')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc')
  const [priceRange, setPriceRange] = useState({ min: '', max: '' })
  const [dateFilter, setDateFilter] = useState('')

  // V2 АКТИВНЫЕ ЗАПРОСЫ - 3 источника данных
  const { data: sellerGoodsData, loading: sellerGoodsLoading, error: sellerGoodsError } = 
    useQuery(GET_MY_SELLER_GOODS_SUPPLY_REQUESTS, {
      fetchPolicy: 'cache-and-network',
    })

  const { data: sellerConsumablesData, loading: sellerConsumablesLoading, error: sellerConsumablesError } = 
    useQuery(GET_MY_SELLER_SUPPLY_REQUESTS, {
      fetchPolicy: 'cache-and-network',
    })

  const { data: fulfillmentConsumablesData, loading: fulfillmentConsumablesLoading, error: fulfillmentConsumablesError } = 
    useQuery(GET_MY_SUPPLIER_CONSUMABLE_SUPPLIES, {
      fetchPolicy: 'cache-and-network',
    })

  // V2 мутации для всех типов действий
  const [updateSellerSupplyStatus] = useMutation(UPDATE_SELLER_SUPPLY_STATUS, {
    refetchQueries: [{ query: GET_MY_SELLER_SUPPLY_REQUESTS }],
    onCompleted: () => toast.success('Статус заказа обновлен'),
    onError: (error) => {
      console.error('Error updating seller supply status:', error)
      toast.error('Ошибка при обновлении статуса заказа')
    },
  })

  const [updateSellerGoodsStatus] = useMutation(UPDATE_SELLER_GOODS_SUPPLY_STATUS, {
    refetchQueries: [{ query: GET_MY_SELLER_GOODS_SUPPLY_REQUESTS }],
    onCompleted: () => toast.success('Статус товарной поставки обновлен'),
    onError: (error) => {
      console.error('Error updating seller goods status:', error)
      toast.error('Ошибка при обновлении статуса товарной поставки')
    },
  })

  const [updateSupplyVolume] = useMutation(UPDATE_SUPPLY_VOLUME_V2, {
    refetchQueries: [{ query: GET_MY_SELLER_GOODS_SUPPLY_REQUESTS }],
    onCompleted: () => toast.success('Объем обновлен'),
    onError: (_error) => toast.error('Ошибка при обновлении объема'),
  })

  const [updateSupplyPackages] = useMutation(UPDATE_SUPPLY_PACKAGES_V2, {
    refetchQueries: [{ query: GET_MY_SELLER_GOODS_SUPPLY_REQUESTS }],
    onCompleted: () => toast.success('Количество упаковок обновлено'),
    onError: (_error) => toast.error('Ошибка при обновлении упаковок'),
  })

  // Мутации для FulfillmentConsumableSupplyOrder
  const [supplierApproveConsumableSupply] = useMutation(SUPPLIER_APPROVE_CONSUMABLE_SUPPLY, {
    refetchQueries: [{ query: GET_MY_SUPPLIER_CONSUMABLE_SUPPLIES }],
    onCompleted: () => toast.success('Заявка на расходники одобрена'),
    onError: (error) => {
      console.error('Error approving consumable supply:', error)
      toast.error('Ошибка при одобрении заявки на расходники')
    },
  })

  const [supplierRejectConsumableSupply] = useMutation(SUPPLIER_REJECT_CONSUMABLE_SUPPLY, {
    refetchQueries: [{ query: GET_MY_SUPPLIER_CONSUMABLE_SUPPLIES }],
    onCompleted: () => toast.success('Заявка на расходники отклонена'),
    onError: (error) => {
      console.error('Error rejecting consumable supply:', error)
      toast.error('Ошибка при отклонении заявки на расходники')
    },
  })

  const [supplierShipConsumableSupply] = useMutation(SUPPLIER_SHIP_CONSUMABLE_SUPPLY, {
    refetchQueries: [{ query: GET_MY_SUPPLIER_CONSUMABLE_SUPPLIES }],
    onCompleted: () => toast.success('Расходники отгружены'),
    onError: (error) => {
      console.error('Error shipping consumable supply:', error)
      toast.error('Ошибка при отгрузке расходников')
    },
  })

  // Адаптер V2 данных под SupplyOrder interface (сохраняем совместимость с UI)
  const adaptV2SupplyToSupplyOrder = useCallback(
    (v2Supply: Record<string, any>, sourceType: string): SupplyOrder => {
    return {
      id: v2Supply.id,
      organizationId: v2Supply.fulfillmentCenterId || v2Supply.sellerId,
      partnerId: v2Supply.sellerId || v2Supply.fulfillmentCenterId,
      deliveryDate: v2Supply.requestedDeliveryDate,
      status: v2Supply.status,
      totalAmount: v2Supply.totalCostWithDelivery || 
        v2Supply.items?.reduce((sum: number, item: any) => sum + (item.totalPrice || 0), 0) || 0,
      totalItems: v2Supply.items?.length || v2Supply.recipeItems?.length || 0,
      fulfillmentCenterId: v2Supply.fulfillmentCenterId,
      logisticsPartnerId: v2Supply.logisticsPartnerId,
      packagesCount: v2Supply.packagesCount,
      volume: v2Supply.estimatedVolume,
      responsibleEmployee: v2Supply.receivedBy?.managerName,
      notes: v2Supply.notes,
      createdAt: v2Supply.createdAt,
      updatedAt: v2Supply.updatedAt,
      partner: {
        id: v2Supply.seller?.id || v2Supply.fulfillmentCenter?.id || '',
        name: v2Supply.seller?.name || v2Supply.fulfillmentCenter?.name,
        fullName: v2Supply.seller?.name || v2Supply.fulfillmentCenter?.name,
        inn: v2Supply.seller?.inn || v2Supply.fulfillmentCenter?.inn || '',
        type: sourceType === 'seller' ? 'SELLER' : 'FULFILLMENT',
      },
      organization: {
        id: v2Supply.supplier?.id || '',
        name: v2Supply.supplier?.name,
        fullName: v2Supply.supplier?.name,
        type: 'WHOLESALE',
      },
      fulfillmentCenter: v2Supply.fulfillmentCenter ? {
        id: v2Supply.fulfillmentCenter.id,
        name: v2Supply.fulfillmentCenter.name,
        fullName: v2Supply.fulfillmentCenter.name,
        type: 'FULFILLMENT',
      } : undefined,
      logisticsPartner: v2Supply.logisticsPartner ? {
        id: v2Supply.logisticsPartner.id,
        name: v2Supply.logisticsPartner.name,
        fullName: v2Supply.logisticsPartner.name,
        type: 'LOGISTICS',
      } : undefined,
      routes: [],
      items: (v2Supply.items || v2Supply.recipeItems || []).map((item: Record<string, any>) => ({
        id: item.id,
        productId: item.productId,
        quantity: item.requestedQuantity || item.quantity,
        price: item.unitPrice || item.price,
        totalPrice: item.totalPrice,
        product: {
          id: item.product?.id || item.productId,
          name: item.product?.name || '',
          article: item.product?.article || '',
        },
      })),
    }
  }, [])

  // V2 объединение всех источников данных
  const supplierOrders: SupplyOrder[] = useMemo(() => {
    const sellerGoodsOrders: SupplyOrder[] = (sellerGoodsData?.mySellerGoodsSupplyRequests || [])
      .map((order: Record<string, any>) => adaptV2SupplyToSupplyOrder(order, 'seller'))
    const sellerConsumablesOrders: SupplyOrder[] = (sellerConsumablesData?.mySellerSupplyRequests || [])
      .map((order: Record<string, any>) => adaptV2SupplyToSupplyOrder(order, 'seller'))
    const fulfillmentConsumablesOrders: SupplyOrder[] = (fulfillmentConsumablesData?.mySupplierConsumableSupplies || [])
      .map((order: Record<string, any>) => adaptV2SupplyToSupplyOrder(order, 'fulfillment'))
    
    // DEBUG: Проверяем данные
    console.warn('🔍 V2 DEBUG DATA:')
    console.warn('Seller Goods:', sellerGoodsData?.mySellerGoodsSupplyRequests?.length || 0)
    console.warn('Seller Consumables:', sellerConsumablesData?.mySellerSupplyRequests?.length || 0)  
    console.warn('Fulfillment Consumables:', fulfillmentConsumablesData?.mySupplierConsumableSupplies?.length || 0)
    console.warn('Total Orders:', sellerGoodsOrders.length + sellerConsumablesOrders.length + fulfillmentConsumablesOrders.length)
    
    return [
      ...sellerGoodsOrders,
      ...sellerConsumablesOrders,
      ...fulfillmentConsumablesOrders,
    ]
  }, [sellerGoodsData, sellerConsumablesData, fulfillmentConsumablesData, adaptV2SupplyToSupplyOrder])

  // V2 обработчики изменения параметров
  const handleVolumeChange = useCallback((supplyId: string, volume: number | null) => {
    if (volume !== null) {
      updateSupplyVolume({ variables: { id: supplyId, volume } })
    }
  }, [updateSupplyVolume])

  const handlePackagesChange = useCallback((supplyId: string, packagesCount: number | null) => {
    if (packagesCount !== null) {
      updateSupplyPackages({ variables: { id: supplyId, packagesCount } })
    }
  }, [updateSupplyPackages])

  // V2 обработчик действий поставщика (умная маршрутизация по типу поставки)
  const handleSupplierAction = async (supplyId: string, action: string) => {
    try {
      // Определяем тип поставки по ID для правильной мутации
      const isSellerGoods = sellerGoodsData?.mySellerGoodsSupplyRequests
        ?.some((s: Record<string, any>) => s.id === supplyId)
      const isSellerConsumables = sellerConsumablesData?.mySellerSupplyRequests
        ?.some((s: Record<string, any>) => s.id === supplyId)
      const isFulfillmentConsumables = fulfillmentConsumablesData?.mySupplierConsumableSupplies
        ?.some((s: Record<string, any>) => s.id === supplyId)

      console.warn('🔍 handleSupplierAction:', { 
        supplyId, 
        action, 
        isSellerGoods, 
        isSellerConsumables, 
        isFulfillmentConsumables, 
      })

      switch (action) {
        case 'approve':
          if (isSellerGoods) {
            await updateSellerGoodsStatus({ variables: { id: supplyId, status: 'APPROVED' } })
          } else if (isSellerConsumables) {
            await updateSellerSupplyStatus({ variables: { id: supplyId, status: 'APPROVED' } })
          } else if (isFulfillmentConsumables) {
            await supplierApproveConsumableSupply({ variables: { id: supplyId } })
          }
          break
        case 'reject':
          const reason = prompt('Укажите причину отклонения заявки:')
          if (reason) {
            if (isSellerGoods) {
              await updateSellerGoodsStatus({ variables: { id: supplyId, status: 'CANCELLED', notes: reason } })
            } else if (isSellerConsumables) {
              await updateSellerSupplyStatus({ variables: { id: supplyId, status: 'CANCELLED', notes: reason } })
            } else if (isFulfillmentConsumables) {
              await supplierRejectConsumableSupply({ variables: { id: supplyId, reason: reason } })
            }
          }
          break
        case 'ship':
          if (isSellerGoods) {
            await updateSellerGoodsStatus({ variables: { id: supplyId, status: 'SHIPPED' } })
          } else if (isSellerConsumables) {
            await updateSellerSupplyStatus({ variables: { id: supplyId, status: 'SHIPPED' } })
          } else if (isFulfillmentConsumables) {
            await supplierShipConsumableSupply({ variables: { id: supplyId } })
          }
          break
        default:
          console.error('Неизвестное действие:', action, supplyId)
      }
    } catch (error) {
      console.error('Ошибка при выполнении действия:', error)
      toast.error('Ошибка при выполнении действия')
    }
  }

  const isLoading = sellerGoodsLoading || sellerConsumablesLoading || fulfillmentConsumablesLoading
  const hasError = sellerGoodsError || sellerConsumablesError || fulfillmentConsumablesError

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-white/60">Загрузка заявок...</div>
      </div>
    )
  }

  if (hasError) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-400">
          Ошибка загрузки заявок: {sellerGoodsError?.message || sellerConsumablesError?.message || fulfillmentConsumablesError?.message}
        </div>
      </div>
    )
  }

  // Точно такая же логика фильтрации как в исходном компоненте
  // Фильтрация (прямой расчет для совместимости хуков)
  let filteredOrders = supplierOrders

  if (searchQuery) {
    const query = searchQuery.toLowerCase()
    filteredOrders = filteredOrders.filter(
      (order) =>
        order.id.toLowerCase().includes(query) ||
        (order.organization.name || '').toLowerCase().includes(query) ||
        (order.organization.fullName || '').toLowerCase().includes(query) ||
        (order.organization.inn || '').toLowerCase().includes(query) ||
        order.items.some((item) =>
          (item.product.name || '').toLowerCase().includes(query) ||
          (item.product.article || '').toLowerCase().includes(query),
        ),
    )
  }

  if (activeTab !== 'all') {
    const statusMap = {
      new: ['PENDING'],
      approved: ['APPROVED', 'LOGISTICS_CONFIRMED'],
      shipping: ['SHIPPED', 'IN_TRANSIT'],
      completed: ['DELIVERED', 'COMPLETED'],
    }
    const targetStatuses = statusMap[activeTab as keyof typeof statusMap] || []
    filteredOrders = filteredOrders.filter((order) => targetStatuses.includes(order.status))
  }

  filteredOrders.sort((a, b) => {
    const aValue = a[sortField as keyof SupplyOrder]
    const bValue = b[sortField as keyof SupplyOrder]
    
    if (aValue === bValue) return 0
    const comparison = aValue > bValue ? 1 : -1
    return sortDirection === 'asc' ? comparison : -comparison
  })

  // Статистика (прямой расчет для совместимости хуков)
  const orderStats = {
    total: supplierOrders.length,
    new: supplierOrders.filter(o => ['PENDING'].includes(o.status)).length,
    approved: supplierOrders.filter(o => ['APPROVED', 'LOGISTICS_CONFIRMED'].includes(o.status)).length,
    shipping: supplierOrders.filter(o => ['SHIPPED', 'IN_TRANSIT'].includes(o.status)).length,
    completed: supplierOrders.filter(o => ['DELIVERED', 'COMPLETED'].includes(o.status)).length,
    totalVolume: supplierOrders.reduce((sum, o) => sum + (o.volume || 0), 0),
    totalAmount: supplierOrders.reduce((sum, o) => sum + (o.totalAmount || 0), 0),
  }

  return (
    <div className="space-y-6">
      {/* Точно такие же статистические карточки */}
      <SupplierOrderStats orders={supplierOrders} />

      {/* Точно такие же табы */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="new" className="flex items-center gap-2">
            <Clock className="h-4 w-4" />
            Новые
            {orderStats.new > 0 && (
              <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] text-xs">
                {orderStats.new}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="approved" className="flex items-center gap-2">
            <CheckCircle className="h-4 w-4" />
            Одобренные
            {orderStats.approved > 0 && (
              <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] text-xs">
                {orderStats.approved}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="shipping" className="flex items-center gap-2">
            <Truck className="h-4 w-4" />
            Отгрузка
            {orderStats.shipping > 0 && (
              <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] text-xs">
                {orderStats.shipping}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="completed" className="flex items-center gap-2">
            <Package className="h-4 w-4" />
            Завершенные
            {orderStats.completed > 0 && (
              <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] text-xs">
                {orderStats.completed}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="all">
            Все заявки
            {orderStats.total > 0 && (
              <Badge variant="secondary" className="ml-1 h-5 min-w-[20px] text-xs">
                {orderStats.total}
              </Badge>
            )}
          </TabsTrigger>
        </TabsList>
      </Tabs>

      {/* Точно такой же поиск */}
      <SupplierOrdersSearch
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        sortField={sortField}
        onSortFieldChange={setSortField}
        sortDirection={sortDirection}
        onSortDirectionChange={setSortDirection}
        priceRange={priceRange}
        onPriceRangeChange={setPriceRange}
        dateFilter={dateFilter}
        onDateFilterChange={setDateFilter}
      />

      {/* Точно такая же таблица */}
      <MultiLevelSuppliesTable
        supplies={filteredOrders}
        userRole="WHOLESALE"
        activeTab={activeTab}
        onSupplyAction={handleSupplierAction}
        onVolumeChange={handleVolumeChange}
        onPackagesChange={handlePackagesChange}
        updating={false}
      />
    </div>
  )
}