'use client'

import { useQuery } from '@apollo/client'
import { Building2, ShoppingCart, Package, Wrench, RotateCcw, Clock, FileText, CheckCircle } from 'lucide-react'
import React, { useState } from 'react'

import { Sidebar } from '@/components/dashboard/sidebar'
import { GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
import { useRealtime } from '@/hooks/useRealtime'
import { useSidebar } from '@/hooks/useSidebar'

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

// Компонент для отображения бейджа с уведомлениями
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 FulfillmentSuppliesDashboard() {
  const { getSidebarMargin } = useSidebar()
  const [activeTab, setActiveTab] = useState('fulfillment')
  const [activeSubTab, setActiveSubTab] = useState('goods') // товар
  const [activeThirdTab, setActiveThirdTab] = useState('new') // новые

  // Загружаем данные о непринятых поставках
  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:', error)
    },
  })

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

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

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

  return (
    <div className="h-screen flex overflow-hidden">
      <Sidebar />
      <main className={`flex-1 ${getSidebarMargin()} px-6 py-4 overflow-hidden transition-all duration-300`}>
        <div className="h-full w-full flex flex-col space-y-4">
          {/* БЛОК 1: ТАБЫ ВСЕХ УРОВНЕЙ */}
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl p-6">
            {/* УРОВЕНЬ 1: Главные табы */}
            <div className="mb-4">
              <div className="grid w-full grid-cols-2 bg-white/15 backdrop-blur border-white/30 rounded-xl h-11 p-2">
                <button
                  onClick={() => setActiveTab('fulfillment')}
                  className={`flex items-center gap-2 text-sm font-semibold transition-all duration-200 rounded-lg px-3 ${
                    activeTab === 'fulfillment'
                      ? 'bg-gradient-to-r from-purple-500/40 to-pink-500/40 text-white shadow-lg'
                      : 'text-white/80 hover:text-white'
                  }`}
                >
                  <Building2 className="h-4 w-4" />
                  <span className="hidden sm:inline">Поставки на фулфилмент</span>
                  <span className="sm:hidden">Фулфилмент</span>
                  <NotificationBadge count={pendingCount} />
                </button>
                <button
                  onClick={() => setActiveTab('marketplace')}
                  className={`flex items-center gap-2 text-sm font-semibold transition-all duration-200 rounded-lg px-3 ${
                    activeTab === 'marketplace'
                      ? 'bg-gradient-to-r from-purple-500/40 to-pink-500/40 text-white shadow-lg'
                      : 'text-white/80 hover:text-white'
                  }`}
                >
                  <ShoppingCart className="h-4 w-4" />
                  <span className="hidden sm:inline">Поставки на маркетплейсы</span>
                  <span className="sm:hidden">Маркетплейсы</span>
                </button>
              </div>
            </div>

            {/* УРОВЕНЬ 2: Подтабы */}
            {activeTab === 'fulfillment' && (
              <div className="ml-4 mb-3">
                <div className="grid w-full grid-cols-5 bg-white/8 backdrop-blur border-white/20 h-9 rounded-lg p-1">
                  <button
                    onClick={() => setActiveSubTab('goods')}
                    className={`flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md px-2 ${
                      activeSubTab === 'goods'
                        ? 'bg-white/15 text-white border-white/20'
                        : 'text-white/60 hover:text-white/80'
                    }`}
                  >
                    <Package className="h-3 w-3" />
                    <span className="hidden sm:inline">Товар</span>
                    <span className="sm:hidden">Т</span>
                  </button>
                  <button
                    onClick={() => setActiveSubTab('detailed-supplies')}
                    className={`flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md px-2 relative ${
                      activeSubTab === 'detailed-supplies'
                        ? 'bg-white/15 text-white border-white/20'
                        : 'text-white/60 hover:text-white/80'
                    }`}
                  >
                    <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} />
                  </button>
                  <button
                    onClick={() => setActiveSubTab('consumables')}
                    className={`flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md px-2 relative ${
                      activeSubTab === 'consumables'
                        ? 'bg-white/15 text-white border-white/20'
                        : 'text-white/60 hover:text-white/80'
                    }`}
                  >
                    <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} />
                  </button>
                  <button
                    onClick={() => setActiveSubTab('returns')}
                    className={`flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md px-2 ${
                      activeSubTab === 'returns'
                        ? 'bg-white/15 text-white border-white/20'
                        : 'text-white/60 hover:text-white/80'
                    }`}
                  >
                    <RotateCcw className="h-3 w-3" />
                    <span className="hidden sm:inline">Возвраты с ПВЗ</span>
                    <span className="sm:hidden">В</span>
                  </button>
                  <button
                    onClick={() => setActiveSubTab('consumables-v2')}
                    className={`flex items-center gap-1 text-xs font-medium transition-all duration-150 rounded-md px-2 ${
                      activeSubTab === 'consumables-v2'
                        ? 'bg-white/15 text-white border-white/20'
                        : 'text-white/60 hover:text-white/80'
                    }`}
                  >
                    <Building2 className="h-3 w-3" />
                    <span className="hidden sm:inline">ФФ v2</span>
                    <span className="sm:hidden">V2</span>
                  </button>
                </div>
              </div>
            )}

            {/* УРОВЕНЬ 3: Подподтабы */}
            {activeTab === 'fulfillment' && activeSubTab === 'goods' && (
              <div className="ml-8">
                <div className="grid w-full grid-cols-3 bg-white/5 backdrop-blur border-white/15 h-8 rounded-md p-1">
                  <button
                    onClick={() => setActiveThirdTab('new')}
                    className={`flex items-center gap-1 text-xs font-normal transition-all duration-150 rounded-sm px-2 ${
                      activeThirdTab === 'new' ? 'bg-white/10 text-white' : 'text-white/50 hover:text-white/70'
                    }`}
                  >
                    <Clock className="h-2.5 w-2.5" />
                    <span className="hidden sm:inline">Новые</span>
                    <span className="sm:hidden">Н</span>
                  </button>
                  <button
                    onClick={() => setActiveThirdTab('receiving')}
                    className={`flex items-center gap-1 text-xs font-normal transition-all duration-150 rounded-sm px-2 ${
                      activeThirdTab === 'receiving' ? 'bg-white/10 text-white' : 'text-white/50 hover:text-white/70'
                    }`}
                  >
                    <FileText className="h-2.5 w-2.5" />
                    <span className="hidden sm:inline">Приёмка</span>
                    <span className="sm:hidden">П</span>
                  </button>
                  <button
                    onClick={() => setActiveThirdTab('received')}
                    className={`flex items-center gap-1 text-xs font-normal transition-all duration-150 rounded-sm px-2 ${
                      activeThirdTab === 'received' ? 'bg-white/10 text-white' : 'text-white/50 hover:text-white/70'
                    }`}
                  >
                    <CheckCircle className="h-2.5 w-2.5" />
                    <span className="hidden sm:inline">Принято</span>
                    <span className="sm:hidden">Пр</span>
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* БЛОК 2: МОДУЛИ СТАТИСТИКИ */}
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl p-6">
            <h3 className="text-white font-semibold mb-4">Статистика</h3>

            {/* Статистика для расходников фулфилмента */}
            {activeTab === 'fulfillment' && activeSubTab === 'detailed-supplies' && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Building2 className="h-5 w-5 text-blue-400" />
                    <div>
                      <p className="text-xs text-white/60">Наши заказы</p>
                      <p className="text-lg font-semibold text-white">{ourSupplyOrdersCount}</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Package className="h-5 w-5 text-green-400" />
                    <div>
                      <p className="text-xs text-white/60">Всего позиций</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Wrench className="h-5 w-5 text-purple-400" />
                    <div>
                      <p className="text-xs text-white/60">На складе</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-5 w-5 text-emerald-400" />
                    <div>
                      <p className="text-xs text-white/60">Доставлено</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Статистика для расходников селлеров */}
            {activeTab === 'fulfillment' && activeSubTab === 'consumables' && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Wrench className="h-5 w-5 text-orange-400" />
                    <div>
                      <p className="text-xs text-white/60">От селлеров</p>
                      <p className="text-lg font-semibold text-white">{sellerSupplyOrdersCount}</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Clock className="h-5 w-5 text-yellow-400" />
                    <div>
                      <p className="text-xs text-white/60">В обработке</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Package className="h-5 w-5 text-blue-400" />
                    <div>
                      <p className="text-xs text-white/60">Принято</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-5 w-5 text-green-400" />
                    <div>
                      <p className="text-xs text-white/60">Использовано</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Статистика для товаров */}
            {activeTab === 'fulfillment' && activeSubTab === 'goods' && (
              <div className="grid grid-cols-3 md:grid-cols-6 gap-4">
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <Clock className="h-5 w-5 text-blue-400" />
                    <div>
                      <p className="text-xs text-white/60">Новые</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <FileText className="h-5 w-5 text-yellow-400" />
                    <div>
                      <p className="text-xs text-white/60">Приёмка</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
                <div className="bg-white/5 backdrop-blur rounded-lg p-4">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-5 w-5 text-green-400" />
                    <div>
                      <p className="text-xs text-white/60">Принято</p>
                      <p className="text-lg font-semibold text-white">-</p>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Общая статистика для других разделов */}
            {activeTab === 'fulfillment' && activeSubTab === 'returns' && (
              <div className="text-white/70">Статистика возвратов с ПВЗ</div>
            )}

            {activeTab === 'marketplace' && <div className="text-white/70">Статистика поставок на маркетплейсы</div>}
          </div>

          {/* БЛОК 3: ОСНОВНОЙ КОНТЕНТ */}
          <div className="flex-1 overflow-hidden">
            <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl h-full overflow-hidden p-6">
              <div className="h-full">
                <h3 className="text-white font-semibold mb-4">
                  Контент: {activeTab} → {activeSubTab} → {activeThirdTab}
                </h3>
                {/* КОНТЕНТ ДЛЯ ТОВАРОВ */}
                {activeTab === 'fulfillment' && activeSubTab === 'goods' && activeThirdTab === 'new' && (
                  <div className="h-full overflow-hidden">
                    <FulfillmentGoodsOrdersTab />
                  </div>
                )}
                {activeTab === 'fulfillment' && activeSubTab === 'goods' && activeThirdTab === 'receiving' && (
                  <div className="text-white/80">Здесь отображаются товары в ПРИЁМКЕ</div>
                )}
                {activeTab === 'fulfillment' && activeSubTab === 'goods' && activeThirdTab === 'received' && (
                  <div className="text-white/80">Здесь отображаются ПРИНЯТЫЕ товары</div>
                )}

                {/* КОНТЕНТ ДЛЯ РАСХОДНИКОВ ФУЛФИЛМЕНТА */}
                {activeTab === 'fulfillment' && activeSubTab === 'detailed-supplies' && (
                  <div className="h-full overflow-hidden">
                    <FulfillmentDetailedSuppliesTab />
                  </div>
                )}

                {/* КОНТЕНТ ДЛЯ РАСХОДНИКОВ СЕЛЛЕРОВ */}
                {activeTab === 'fulfillment' && activeSubTab === 'consumables' && (
                  <div className="h-full overflow-hidden">
                    <FulfillmentConsumablesOrdersTab />
                  </div>
                )}

                {/* КОНТЕНТ ДЛЯ ВОЗВРАТОВ С ПВЗ */}
                {activeTab === 'fulfillment' && activeSubTab === 'returns' && (
                  <div className="h-full overflow-hidden">
                    <PvzReturnsTab />
                  </div>
                )}

                {/* КОНТЕНТ ДЛЯ НОВОЙ СИСТЕМЫ ПОСТАВОК V2 */}
                {activeTab === 'fulfillment' && activeSubTab === 'consumables-v2' && (
                  <div className="h-full overflow-hidden">
                    <div className="text-center py-12">
                      <Building2 className="h-16 w-16 text-white/40 mx-auto mb-6" />
                      <h3 className="text-xl font-semibold text-white mb-4">
                        Система поставок расходников V2
                      </h3>
                      <p className="text-white/60 mb-6 max-w-md mx-auto">
                        Создавайте заявки на расходники для фулфилмент-центра через новую систему V2
                      </p>
                      <a 
                        href="/supplies/create-fulfillment-consumables-v2"
                        className="inline-flex items-center gap-2 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 shadow-lg hover:shadow-xl"
                      >
                        <Package className="h-5 w-5" />
                        Создать поставку V2
                      </a>
                    </div>
                  </div>
                )}

                {/* КОНТЕНТ ДЛЯ МАРКЕТПЛЕЙСОВ */}
                {activeTab === 'marketplace' && (
                  <div className="text-white/80">Содержимое поставок на маркетплейсы</div>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
