'use client'
/* eslint-disable @typescript-eslint/no-explicit-any */

import { Package, TrendingUp } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'

import { LoadingSkeleton } from './loading-skeleton'
import { SearchBar } from './search-bar'
import { StatsCards } from './stats-cards'
import { StockTableRow } from './stock-table-row'
import { TableHeader } from './table-header'

interface WBStock {
  nmId: number
  vendorCode: string
  title: string
  brand: string
  price: number
  stocks: Array<{
    warehouseId: number
    warehouseName: string
    quantity: number
    quantityFull: number
    inWayToClient: number
    inWayFromClient: number
  }>
  totalQuantity: number
  totalReserved: number
  photos: any[]
  mediaFiles: any[]
  characteristics: any[]
  subjectName: string
  description: string
}

interface WBWarehouse {
  id: number
  name: string
  cargoType: number
  deliveryType: number
}

interface WildberriesWarehouseTabProps {
  stocks: WBStock[]
  warehouses: WBWarehouse[]
  loading: boolean
  initialized: boolean
  cacheLoading: boolean
  totalProducts: number
  totalStocks: number
  totalReserved: number
  totalFromClient: number
  activeWarehouses: number
  analyticsData: any[]
  onRefresh: () => Promise<void>
}

export function WildberriesWarehouseTab({
  stocks,
  warehouses: _warehouses,
  loading,
  initialized,
  cacheLoading,
  totalProducts,
  totalStocks,
  totalReserved,
  totalFromClient,
  activeWarehouses,
  analyticsData,
  onRefresh,
}: WildberriesWarehouseTabProps) {
  const [searchTerm, setSearchTerm] = useState('')

  // Фильтрация товаров
  const filteredStocks = stocks.filter((item) => {
    if (!searchTerm) return true
    const search = searchTerm.toLowerCase()
    return (
      item.title.toLowerCase().includes(search) ||
      String(item.nmId).includes(search) ||
      item.brand.toLowerCase().includes(search) ||
      item.vendorCode.toLowerCase().includes(search)
    )
  })

  const handleRefresh = async () => {
    try {
      await onRefresh()
    } catch (error) {
      console.error('Error refreshing data:', error)
      toast.error('Ошибка при обновлении данных')
    }
  }

  return (
    <div className="h-full flex flex-col overflow-hidden min-h-0">
      {/* Статистика */}
      <div className="flex-shrink-0">
        <StatsCards
          totalProducts={totalProducts}
          totalStocks={totalStocks}
          totalReserved={totalReserved}
          totalFromClient={totalFromClient}
          activeWarehouses={activeWarehouses}
          loading={!initialized || loading || cacheLoading}
        />
      </div>

      {/* Аналитика по складам WB */}
      {initialized && analyticsData.length > 0 && (
        <div className="flex-shrink-0 mb-4">
          <Card className="glass-card border-white/10 p-4">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
              <TrendingUp className="h-5 w-5 mr-2 text-blue-400" />
              Аналитика по складам WB
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {analyticsData.slice(0, 6).map((item, index) => (
                <div key={index} className="bg-white/5 rounded-lg p-3">
                  <div className="text-sm text-white/60">Склад {index + 1}</div>
                  <div className="text-lg font-medium text-white">
                    {JSON.stringify(item).length > 50
                      ? `${JSON.stringify(item).substring(0, 50)}...`
                      : JSON.stringify(item)}
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>
      )}

      {/* Основной контент */}
      <Card className="glass-card border-white/10 flex-1 flex flex-col overflow-hidden min-h-0">
        <div className="p-6 border-b border-white/10 flex-shrink-0">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
              <h2 className="text-xl font-semibold text-white flex items-center">
                <Package className="h-6 w-6 mr-2 text-blue-400" />
                Склад Wildberries
              </h2>
              <p className="text-white/60 text-sm mt-1">Управление товарами на складах Wildberries</p>
            </div>
            <div className="flex gap-3">
              <Button onClick={handleRefresh} disabled={loading} className="bg-blue-600 hover:bg-blue-700 text-white">
                {loading ? 'Обновление...' : 'Обновить данные'}
              </Button>
            </div>
          </div>

          {/* Поиск */}
          <div className="mt-4">
            <SearchBar searchTerm={searchTerm} onSearchChange={setSearchTerm} />
          </div>
        </div>

        {/* Контент с таблицей */}
        <div className="flex-1 overflow-hidden min-h-0">
          {!initialized || loading || cacheLoading ? (
            <div className="p-6">
              <LoadingSkeleton />
            </div>
          ) : filteredStocks.length === 0 ? (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Package className="h-12 w-12 text-white/20 mx-auto mb-4" />
                <p className="text-white/60">{searchTerm ? 'Товары не найдены' : 'Нет данных о товарах'}</p>
                {!searchTerm && (
                  <Button onClick={handleRefresh} className="mt-4 bg-blue-600 hover:bg-blue-700 text-white">
                    Загрузить данные
                  </Button>
                )}
              </div>
            </div>
          ) : (
            <div className="h-full overflow-y-auto">
              <div className="p-6 space-y-3">
                {/* Заголовок таблицы */}
                <TableHeader />

                {/* Строки товаров */}
                {filteredStocks.map((item) => (
                  <StockTableRow key={item.nmId} item={item} />
                ))}
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  )
}
