// =============================================================================
// 📦 БЛОК РАСХОДНИКОВ
// =============================================================================
// ВНИМАНИЕ: Визуал остается ТОЧНО таким же как в монолитной версии!
// Все gradients, glassmorphism, анимации, индикаторы остатков сохранены

import { Search, Wrench, Package, Plus, Minus } from 'lucide-react'
import Image from 'next/image'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'

import type { FulfillmentConsumableProduct } from '../types'

import type { ConsumablesBlockProps } from './types'

export function ConsumablesBlock({
  selectedSupplier,
  products,
  productsLoading,
  productSearchQuery,
  getSelectedQuantity,
  onProductSearchChange,
  onUpdateQuantity,
  formatCurrency,
}: ConsumablesBlockProps) {
  return (
    <Card className="bg-white/10 backdrop-blur border-white/20 flex-1 min-h-0 flex flex-col">
      <div className="p-3 border-b border-white/10 flex-shrink-0">
        <div className="flex items-center justify-between mb-2">
          <h2 className="text-lg font-semibold text-white flex items-center">
            <Wrench className="h-4 w-4 mr-2" />
            Расходники для фулфилмента
            {selectedSupplier && (
              <span className="text-white/60 text-xs font-normal ml-2 truncate">
                - {selectedSupplier.name || selectedSupplier.fullName}
              </span>
            )}
          </h2>
        </div>
        {selectedSupplier && (
          <div className="relative">
            <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-white/40 h-3 w-3" />
            <Input
              placeholder="Поиск расходников..."
              value={productSearchQuery}
              onChange={(e) => onProductSearchChange(e.target.value)}
              className="bg-white/10 border-white/20 text-white placeholder-white/40 pl-7 h-8 text-sm"
            />
          </div>
        )}
      </div>

      <div className="p-3 flex-1 overflow-y-auto">
        {!selectedSupplier ? (
          <div className="text-center py-8">
            <Wrench className="h-8 w-8 text-white/40 mx-auto mb-3" />
            <p className="text-white/60 text-sm">Выберите поставщика для просмотра расходников</p>
          </div>
        ) : productsLoading ? (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-6 w-6 border-2 border-white border-t-transparent mx-auto mb-2"></div>
            <p className="text-white/60 text-sm">Загрузка...</p>
          </div>
        ) : products.length === 0 ? (
          <div className="text-center py-8">
            <Package className="h-8 w-8 text-white/40 mx-auto mb-3" />
            <p className="text-white/60 text-sm">Нет доступных расходников</p>
          </div>
        ) : (
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-7 gap-3">
            {products.map((product: FulfillmentConsumableProduct, index: number) => {
              const selectedQuantity = getSelectedQuantity(product.id)
              return (
                <Card
                  key={product.id}
                  className={`relative bg-gradient-to-br from-white/10 via-white/5 to-white/10 backdrop-blur border border-white/20 p-3 rounded-xl overflow-hidden group hover:shadow-xl transition-all duration-300 ${
                    selectedQuantity > 0
                      ? 'ring-2 ring-green-400/50 bg-gradient-to-br from-green-500/20 via-green-400/10 to-green-500/20'
                      : 'hover:from-white/20 hover:via-white/10 hover:to-white/20 hover:border-white/40'
                  }`}
                  style={{
                    animationDelay: `${index * 50}ms`,
                    minHeight: '200px',
                    width: '100%',
                  }}
                >
                  <div className="space-y-2 h-full flex flex-col">
                    {/* Изображение товара */}
                    <div className="aspect-square bg-white/5 rounded-lg overflow-hidden relative flex-shrink-0">
                      {/* 🚫 ОВЕРЛЕЙ НЕДОСТУПНОСТИ */}
                      {(() => {
                        const totalStock = product.stock || (product as any).quantity || 0
                        const orderedStock = (product as any).ordered || 0
                        const availableStock = totalStock - orderedStock

                        if (availableStock <= 0) {
                          return (
                            <div className="absolute inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-10">
                              <div className="text-center">
                                <div className="text-red-400 font-bold text-xs">НЕТ В НАЛИЧИИ</div>
                              </div>
                            </div>
                          )
                        }
                        return null
                      })()}
                      {product.images && product.images.length > 0 && product.images[0] ? (
                        <Image
                          src={product.images[0]}
                          alt={product.name}
                          width={100}
                          height={100}
                          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
                        />
                      ) : product.mainImage ? (
                        <Image
                          src={product.mainImage}
                          alt={product.name}
                          width={100}
                          height={100}
                          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
                        />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center">
                          <Wrench className="h-8 w-8 text-white/40" />
                        </div>
                      )}
                      {selectedQuantity > 0 && (
                        <div className="absolute top-2 right-2 bg-gradient-to-r from-green-400 to-green-500 rounded-full w-6 h-6 flex items-center justify-center shadow-lg animate-pulse">
                          <span className="text-white text-xs font-bold">
                            {selectedQuantity > 999 ? '999+' : selectedQuantity}
                          </span>
                        </div>
                      )}
                    </div>

                    {/* Информация о товаре */}
                    <div className="space-y-1 flex-grow">
                      <h3 className="text-white font-medium text-sm leading-tight line-clamp-2 group-hover:text-purple-200 transition-colors duration-300">
                        {product.name}
                      </h3>
                      <div className="flex items-center gap-2 flex-wrap">
                        {product.category && (
                          <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-xs px-2 py-1">
                            {product.category.name.slice(0, 10)}
                          </Badge>
                        )}
                        {/* 🚨 ИНДИКАТОР НИЗКИХ ОСТАТКОВ согласно правилам (раздел 6.3) */}
                        {(() => {
                          const totalStock = product.stock || product.quantity || 0
                          const orderedStock = product.ordered || 0
                          const availableStock = totalStock - orderedStock

                          if (availableStock <= 0) {
                            return (
                              <Badge className="bg-red-500/30 text-red-300 border-red-500/50 text-xs px-2 py-1 animate-pulse">
                                Нет в наличии
                              </Badge>
                            )
                          } else if (availableStock <= 10) {
                            return (
                              <Badge className="bg-yellow-500/30 text-yellow-300 border-yellow-500/50 text-xs px-2 py-1">
                                Мало остатков
                              </Badge>
                            )
                          }
                          return null
                        })()}
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-green-400 font-semibold text-sm">
                          {formatCurrency(product.price)}
                        </span>
                        {/* 📊 АКТУАЛЬНЫЙ ОСТАТОК согласно правилам (раздел 6.4.2) */}
                        <div className="text-right">
                          {(() => {
                            const totalStock = product.stock || product.quantity || 0
                            const orderedStock = product.ordered || 0
                            const availableStock = totalStock - orderedStock

                            return (
                              <div className="flex flex-col items-end">
                                <span
                                  className={`text-xs font-medium ${
                                    availableStock <= 0
                                      ? 'text-red-400'
                                      : availableStock <= 10
                                        ? 'text-yellow-400'
                                        : 'text-white/80'
                                  }`}
                                >
                                  Доступно: {availableStock}
                                </span>
                                {orderedStock > 0 && (
                                  <span className="text-white/40 text-xs">Заказано: {orderedStock}</span>
                                )}
                              </div>
                            )
                          })()}
                        </div>
                      </div>
                    </div>

                    {/* Управление количеством */}
                    <div className="flex flex-col items-center space-y-2 mt-auto">
                      {(() => {
                        const totalStock = product.stock || (product as any).quantity || 0
                        const orderedStock = (product as any).ordered || 0
                        const availableStock = totalStock - orderedStock

                        return (
                          <div className="flex items-center space-x-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() =>
                                onUpdateQuantity(product.id, Math.max(0, selectedQuantity - 1))
                              }
                              className="h-6 w-6 p-0 text-white/60 hover:text-white hover:bg-white/20 rounded-full transition-all duration-300"
                              disabled={selectedQuantity === 0}
                            >
                              <Minus className="h-3 w-3" />
                            </Button>
                            <Input
                              type="text"
                              inputMode="numeric"
                              pattern="[0-9]*"
                              value={selectedQuantity === 0 ? '' : selectedQuantity.toString()}
                              onChange={(e) => {
                                let inputValue = e.target.value

                                // Удаляем все нецифровые символы
                                inputValue = inputValue.replace(/[^0-9]/g, '')

                                // Удаляем ведущие нули
                                inputValue = inputValue.replace(/^0+/, '')

                                // Если строка пустая после удаления нулей, устанавливаем 0
                                const numericValue = inputValue === '' ? 0 : parseInt(inputValue)

                                // Ограничиваем значение максимумом доступного остатка
                                const clampedValue = Math.min(numericValue, availableStock, 99999)

                                onUpdateQuantity(product.id, clampedValue)
                              }}
                              onBlur={(e) => {
                                // При потере фокуса, если поле пустое, устанавливаем 0
                                if (e.target.value === '') {
                                  onUpdateQuantity(product.id, 0)
                                }
                              }}
                              className="w-16 h-7 text-center text-sm bg-white/10 border-white/20 text-white rounded px-1 focus:ring-2 focus:ring-purple-400/50 focus:border-purple-400/50"
                              placeholder="0"
                            />
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() =>
                                onUpdateQuantity(
                                  product.id,
                                  Math.min(selectedQuantity + 1, availableStock, 99999),
                                )
                              }
                              className={`h-6 w-6 p-0 rounded-full transition-all duration-300 ${
                                selectedQuantity >= availableStock || availableStock <= 0
                                  ? 'text-white/30 cursor-not-allowed'
                                  : 'text-white/60 hover:text-white hover:bg-white/20'
                              }`}
                              disabled={selectedQuantity >= availableStock || availableStock <= 0}
                              title={
                                availableStock <= 0
                                  ? 'Товар отсутствует на складе'
                                  : selectedQuantity >= availableStock
                                    ? `Максимум доступно: ${availableStock}`
                                    : 'Увеличить количество'
                              }
                            >
                              <Plus className="h-3 w-3" />
                            </Button>
                          </div>
                        )
                      })()}

                      {selectedQuantity > 0 && (
                        <div className="text-center">
                          <span className="text-green-400 font-bold text-sm bg-green-500/10 px-3 py-1 rounded-full">
                            {formatCurrency(product.price * selectedQuantity)}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Hover эффект */}
                  <div className="absolute inset-0 bg-gradient-to-br from-purple-500/0 to-pink-500/0 group-hover:from-purple-500/5 group-hover:to-pink-500/5 transition-all duration-300 pointer-events-none rounded-xl"></div>
                </Card>
              )
            })}
          </div>
        )}
      </div>
    </Card>
  )
}