'use client'

import { Package, ShoppingCart, Truck, CheckCircle, AlertTriangle, TrendingUp, TrendingDown } from 'lucide-react'
import React from 'react'

import { Badge } from '@/components/ui/badge'
import { Card } from '@/components/ui/card'

interface Product {
  id: string
  name: string
  article: string
  type: 'PRODUCT' | 'CONSUMABLE'
  quantity: number
  ordered?: number
  inTransit?: number
  stock?: number
  sold?: number
  isActive: boolean
}

interface WarehouseStatisticsProps {
  products: Product[]
}

export function WarehouseStatistics({ products }: WarehouseStatisticsProps) {
  console.warn('📊 STATISTICS DEBUG:', { productsCount: products.length, products })

  // Разделение товаров по типам
  const goods = products.filter((p) => p.type === 'PRODUCT')
  const consumables = products.filter((p) => p.type === 'CONSUMABLE')

  // Общая статистика
  const totalProducts = products.length
  const activeProducts = products.filter((p) => p.isActive).length
  const totalStock = products.reduce((sum, p) => sum + (p.stock || p.quantity || 0), 0)
  const totalOrdered = products.reduce((sum, p) => sum + (p.ordered || 0), 0)
  const totalInTransit = products.reduce((sum, p) => sum + (p.inTransit || 0), 0)
  const _totalSold = products.reduce((sum, p) => sum + (p.sold || 0), 0)

  // Статистика по товарам
  const goodsStock = goods.reduce((sum, p) => sum + (p.stock || p.quantity || 0), 0)
  const _goodsOrdered = goods.reduce((sum, p) => sum + (p.ordered || 0), 0)
  const _goodsInTransit = goods.reduce((sum, p) => sum + (p.inTransit || 0), 0)
  const goodsSold = goods.reduce((sum, p) => sum + (p.sold || 0), 0)

  // Статистика по расходникам
  const consumablesStock = consumables.reduce((sum, p) => sum + (p.stock || p.quantity || 0), 0)
  const _consumablesOrdered = consumables.reduce((sum, p) => sum + (p.ordered || 0), 0)
  const _consumablesInTransit = consumables.reduce((sum, p) => sum + (p.inTransit || 0), 0)
  const consumablesSold = consumables.reduce((sum, p) => sum + (p.sold || 0), 0)

  // Товары с низкими остатками
  const lowStockProducts = products.filter((p) => {
    const stock = p.stock || p.quantity || 0
    return stock > 0 && stock < 10
  })

  const outOfStockProducts = products.filter((p) => {
    const stock = p.stock || p.quantity || 0
    return stock === 0
  })

  const StatCard = ({
    icon: Icon,
    title,
    value,
    subtitle,
    trend,
    color = 'text-white',
  }: {
    icon: any
    title: string
    value: number
    subtitle?: string
    trend?: 'up' | 'down'
    color?: string
  }) => (
    <Card className="bg-white/5 backdrop-blur border-white/10 p-4">
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Icon className={`h-4 w-4 ${color}`} />
            <span className="text-white/70 text-sm">{title}</span>
          </div>
          <div className="text-2xl font-bold text-white">{value.toLocaleString()}</div>
          {subtitle && <div className="text-white/60 text-xs mt-1">{subtitle}</div>}
        </div>
        {trend && (
          <div className="text-right">
            {trend === 'up' ? (
              <TrendingUp className="h-4 w-4 text-green-400" />
            ) : (
              <TrendingDown className="h-4 w-4 text-red-400" />
            )}
          </div>
        )}
      </div>
    </Card>
  )

  return (
    <div className="space-y-4">
      {/* Общая статистика */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard
          icon={Package}
          title="Всего позиций"
          value={totalProducts}
          subtitle={`Активных: ${activeProducts}`}
          color="text-blue-400"
        />
        <StatCard
          icon={CheckCircle}
          title="Остаток"
          value={totalStock}
          subtitle="штук на складе"
          color="text-green-400"
        />
        <StatCard
          icon={ShoppingCart}
          title="Заказано"
          value={totalOrdered}
          subtitle="штук в заказах"
          color="text-yellow-400"
        />
        <StatCard
          icon={Truck}
          title="В пути"
          value={totalInTransit}
          subtitle="штук доставляется"
          color="text-purple-400"
        />
      </div>

      {/* Статистика по типам */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Товары */}
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Package className="h-4 w-4 text-blue-400" />
            <h3 className="text-sm font-semibold text-white">Товары</h3>
            <Badge className="bg-blue-500/20 text-blue-300 border-blue-400/30 text-xs">{goods.length}</Badge>
          </div>
          <div className="grid grid-cols-2 gap-2">
            <div className="bg-white/5 backdrop-blur border-white/10 p-2 rounded">
              <div className="text-xs text-white/70">Остаток</div>
              <div className="text-sm font-bold text-green-400">{goodsStock}</div>
            </div>
            <div className="bg-white/5 backdrop-blur border-white/10 p-2 rounded">
              <div className="text-xs text-white/70">Продано</div>
              <div className="text-sm font-bold text-emerald-400">{goodsSold}</div>
            </div>
          </div>
        </div>

        {/* Расходники */}
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Package className="h-4 w-4 text-orange-400" />
            <h3 className="text-sm font-semibold text-white">Расходники</h3>
            <Badge className="bg-orange-500/20 text-orange-300 border-orange-400/30 text-xs">
              {consumables.length}
            </Badge>
          </div>
          <div className="grid grid-cols-2 gap-2">
            <div className="bg-white/5 backdrop-blur border-white/10 p-2 rounded">
              <div className="text-xs text-white/70">Остаток</div>
              <div className="text-sm font-bold text-green-400">{consumablesStock}</div>
            </div>
            <div className="bg-white/5 backdrop-blur border-white/10 p-2 rounded">
              <div className="text-xs text-white/70">Продано</div>
              <div className="text-sm font-bold text-emerald-400">{consumablesSold}</div>
            </div>
          </div>
        </div>
      </div>

      {/* Уведомления о низких остатках */}
      {(lowStockProducts.length > 0 || outOfStockProducts.length > 0) && (
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-yellow-400" />
            <h3 className="text-sm font-semibold text-white">Предупреждения</h3>
          </div>

          {outOfStockProducts.length > 0 && (
            <Card className="bg-red-500/10 backdrop-blur border-red-400/30 p-3">
              <div className="flex items-center gap-2 mb-2">
                <AlertTriangle className="h-4 w-4 text-red-400" />
                <span className="text-red-300 font-medium text-sm">Нет в наличии ({outOfStockProducts.length})</span>
              </div>
              <div className="space-y-1">
                {outOfStockProducts.slice(0, 3).map((product) => (
                  <div key={product.id} className="text-red-200 text-xs">
                    • {product.name} (арт. {product.article})
                  </div>
                ))}
                {outOfStockProducts.length > 3 && (
                  <div className="text-red-300 text-xs">и ещё {outOfStockProducts.length - 3} товаров...</div>
                )}
              </div>
            </Card>
          )}

          {lowStockProducts.length > 0 && (
            <Card className="bg-yellow-500/10 backdrop-blur border-yellow-400/30 p-3">
              <div className="flex items-center gap-2 mb-2">
                <AlertTriangle className="h-4 w-4 text-yellow-400" />
                <span className="text-yellow-300 font-medium text-sm">Мало на складе ({lowStockProducts.length})</span>
              </div>
              <div className="space-y-1">
                {lowStockProducts.slice(0, 3).map((product) => {
                  const stock = product.stock || product.quantity || 0
                  return (
                    <div key={product.id} className="text-yellow-200 text-xs">
                      • {product.name} (арт. {product.article}) - {stock} шт.
                    </div>
                  )
                })}
                {lowStockProducts.length > 3 && (
                  <div className="text-yellow-300 text-xs">и ещё {lowStockProducts.length - 3} товаров...</div>
                )}
              </div>
            </Card>
          )}
        </div>
      )}
    </div>
  )
}
