'use client'

import { useQuery } from '@apollo/client'
import { Package, Wrench, RotateCcw, Building2 } from 'lucide-react'
import { useSearchParams, useRouter } from 'next/navigation'
import React, { useState, useEffect } from 'react'

import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
import { useRealtime } from '@/hooks/useRealtime'

// Импорты компонентов подкатегорий
import { FulfillmentConsumablesOrdersTab } from './fulfillment-consumables-orders-tab'
import { FulfillmentDetailedSuppliesTab } from './fulfillment-detailed-supplies-tab'
import { FulfillmentGoodsTab } from './fulfillment-goods-tab'
import { PvzReturnsTab } from './pvz-returns-tab'

// Новые компоненты для детального просмотра (копия из supplies модуля)

// Компонент для отображения бейджа с уведомлениями
function NotificationBadge({ count }: { count: number }) {
  if (count === 0) return null

  return (
    <div className="ml-1 bg-red-500 text-white text-xs font-bold rounded-full min-w-[16px] h-4 flex items-center justify-center px-1">
      {count > 99 ? '99+' : count}
    </div>
  )
}

export function FulfillmentSuppliesTab() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [activeTab, setActiveTab] = useState('goods')

  // Загружаем данные о непринятых поставках
  const { data: pendingData, error: pendingError, refetch: refetchPending } = useQuery(GET_PENDING_SUPPLIES_COUNT, {
    fetchPolicy: 'cache-first',
    errorPolicy: 'ignore',
    onError: (error) => {
      console.error('❌ GET_PENDING_SUPPLIES_COUNT Error in FulfillmentSuppliesTab:', error)
    },
  })

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

  // Логируем ошибку для диагностики
  React.useEffect(() => {
    if (pendingError) {
      console.error('🚨 Ошибка загрузки счетчиков в FulfillmentSuppliesTab:', pendingError)
    }
  }, [pendingError])

  // ✅ ПРАВИЛЬНО: Для фулфилмента считаем только поставки, НЕ заявки на партнерство
  const pendingCount = pendingData?.pendingSuppliesCount?.supplyOrders || 0
  const ourSupplyOrdersCount = pendingData?.pendingSuppliesCount?.ourSupplyOrders || 0
  const sellerSupplyOrdersCount = pendingData?.pendingSuppliesCount?.sellerSupplyOrders || 0

  // Проверяем URL параметр при загрузке
  useEffect(() => {
    const tabParam = searchParams.get('tab')
    if (tabParam && ['goods', 'detailed-supplies', 'consumables', 'returns'].includes(tabParam)) {
      setActiveTab(tabParam)
    }
  }, [searchParams])

  // Обновляем URL при смене вкладки
  const handleTabChange = (newTab: string) => {
    setActiveTab(newTab)
    const currentPath = window.location.pathname
    const newUrl = `${currentPath}?tab=${newTab}`
    router.replace(newUrl)
  }

  return (
    <div className="space-y-3">
      {/* УРОВЕНЬ 2: Подтабы (средний размер, отступ показывает иерархию) */}
      <div className="ml-4">
        <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
          <TabsList className="grid w-full grid-cols-4 bg-white/8 backdrop-blur border-white/20 h-9 rounded-lg p-1 mb-3">
            <TabsTrigger
              value="goods"
              className="data-[state=active]:bg-white/15 data-[state=active]:text-white data-[state=active]:border-white/20 text-white/60 hover:text-white/80 flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md"
            >
              <Package className="h-3 w-3" />
              <span className="hidden sm:inline">Товар</span>
              <span className="sm:hidden">Т</span>
            </TabsTrigger>
            <TabsTrigger
              value="detailed-supplies"
              className="data-[state=active]:bg-white/15 data-[state=active]:text-white data-[state=active]:border-white/20 text-white/60 hover:text-white/80 flex items-center gap-1 text-xs font-medium transition-all duration-150 relative rounded-md"
            >
              <Building2 className="h-3 w-3" />
              <span className="hidden md:inline">Расходники фулфилмента</span>
              <span className="md:hidden hidden sm:inline">Фулфилмент</span>
              <span className="sm:hidden">Ф</span>
              <NotificationBadge count={ourSupplyOrdersCount} />
            </TabsTrigger>
            <TabsTrigger
              value="consumables"
              className="data-[state=active]:bg-white/15 data-[state=active]:text-white data-[state=active]:border-white/20 text-white/60 hover:text-white/80 flex items-center gap-1 text-xs font-medium transition-all duration-150 relative rounded-md"
            >
              <Wrench className="h-3 w-3" />
              <span className="hidden md:inline">Расходники селлеров</span>
              <span className="md:hidden hidden sm:inline">Селлеры</span>
              <span className="sm:hidden">С</span>
              <NotificationBadge count={sellerSupplyOrdersCount} />
            </TabsTrigger>
            <TabsTrigger
              value="returns"
              className="data-[state=active]:bg-white/15 data-[state=active]:text-white data-[state=active]:border-white/20 text-white/60 hover:text-white/80 flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md"
            >
              <RotateCcw className="h-3 w-3" />
              <span className="hidden sm:inline">Возвраты с ПВЗ</span>
              <span className="sm:hidden">В</span>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="goods" className="space-y-0">
            <FulfillmentGoodsTab />
          </TabsContent>

          <TabsContent value="detailed-supplies" className="space-y-0">
            <div className="p-4">
              <FulfillmentDetailedSuppliesTab />
            </div>
          </TabsContent>

          <TabsContent value="consumables" className="space-y-0">
            <div className="p-4">
              <FulfillmentConsumablesOrdersTab />
            </div>
          </TabsContent>

          <TabsContent value="returns" className="space-y-0">
            <PvzReturnsTab />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}
