'use client'

import { Package } from 'lucide-react'
import React from 'react'

// Интерфейсы (можно будет вынести в отдельный файл types.ts)
interface WBStockInfo {
  warehouseId: number
  warehouseName: string
  quantity: number
  quantityFull: number
  inWayToClient: number
  inWayFromClient: number
}

interface WBStock {
  nmId: number
  vendorCode: string
  title: string
  brand: string
  price: number
  stocks: WBStockInfo[]
  totalQuantity: number
  totalReserved: number
  photos: unknown[]
  mediaFiles: unknown[]
  characteristics: unknown[]
  subjectName: string
  description: string
}

interface StockTableRowProps {
  item: WBStock
}

export function StockTableRow({ item }: StockTableRowProps) {
  // Функция для получения изображений карточки
  const getCardImages = (item: WBStock) => {
    const fallbackUrl = `https://basket-${String(item.nmId).slice(
      0,
      2,
    )}.wbbasket.ru/vol${String(item.nmId).slice(0, -5)}/part${String(item.nmId).slice(
      0,
      -3,
    )}/${item.nmId}/images/big/1.webp`

    // Проверяем photos
    if (item.photos && item.photos.length > 0) {
      return item.photos.map(
        (photo) => photo.big || photo.c516x688 || photo.c246x328 || photo.square || photo.tm || fallbackUrl,
      )
    }

    // Проверяем mediaFiles
    if (item.mediaFiles && item.mediaFiles.length > 0) {
      return item.mediaFiles.map(
        (media) => media.big || media.c516x688 || media.c246x328 || media.square || media.tm || fallbackUrl,
      )
    }

    return [fallbackUrl]
  }

  const getStockStatus = (quantity: number) => {
    if (quantity === 0)
      return {
        color: 'text-red-400',
        bgColor: 'bg-red-500/10',
        label: 'Нет в наличии',
      }
    if (quantity < 10)
      return {
        color: 'text-orange-400',
        bgColor: 'bg-orange-500/10',
        label: 'Мало',
      }
    return {
      color: 'text-green-400',
      bgColor: 'bg-green-500/10',
      label: 'В наличии',
    }
  }

  const stockStatus = getStockStatus(item.totalQuantity)
  const images = getCardImages(item)
  const mainImage = images[0] || null

  // Отбираем ключевые характеристики для отображения в таблице
  const keyCharacteristics = item.characteristics?.slice(0, 3) || []

  return (
    <div className="group">
      {/* Основная строка товара */}
      <div className="grid grid-cols-12 gap-4 p-4 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 hover:border-white/20 transition-all duration-300">
        {/* Товар (3 колонки) */}
        <div className="col-span-3 flex items-center gap-3">
          <div className="w-12 h-12 rounded-lg overflow-hidden bg-white/10 flex-shrink-0">
            {mainImage ? (
              <img
                src={mainImage}
                alt={item.title}
                className="w-full h-full object-cover"
                onError={(e) => {
                  const target = e.target as HTMLImageElement
                  target.src = `https://basket-${String(item.nmId).slice(0, 2)}.wbbasket.ru/vol${String(
                    item.nmId,
                  ).slice(0, -5)}/part${String(item.nmId).slice(0, -3)}/${item.nmId}/images/big/1.webp`
                }}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center">
                <Package className="h-5 w-5 text-white/40" />
              </div>
            )}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <span className="text-xs text-blue-300 bg-blue-500/20 px-2 py-0.5 rounded">
                {item.brand || 'Без бренда'}
              </span>
              <span className="text-white/40 text-xs">#{item.nmId}</span>
            </div>
            <h3 className="text-white text-sm font-medium line-clamp-1 mb-1">{item.title}</h3>
            <div className="text-white/60 text-xs">{item.vendorCode}</div>
          </div>
        </div>

        {/* Остаток */}
        <div className="col-span-1 flex items-center justify-center">
          <div className="text-center">
            <div className={`text-lg font-bold ${stockStatus.color}`}>{item.totalQuantity.toLocaleString()}</div>
            <div className={`text-xs px-2 py-0.5 rounded ${stockStatus.bgColor} ${stockStatus.color}`}>
              {stockStatus.label}
            </div>
          </div>
        </div>

        {/* К клиенту */}
        <div className="col-span-1 flex items-center justify-center">
          <div className="text-center">
            <div className="text-lg font-bold text-orange-400">
              {item.stocks.reduce((sum, s) => sum + s.inWayToClient, 0)}
            </div>
            <div className="text-xs text-white/60">в пути</div>
          </div>
        </div>

        {/* От клиента */}
        <div className="col-span-1 flex items-center justify-center">
          <div className="text-center">
            <div className="text-lg font-bold text-red-400">
              {item.stocks.reduce((sum, s) => sum + s.inWayFromClient, 0)}
            </div>
            <div className="text-xs text-white/60">возвраты</div>
          </div>
        </div>

        {/* Складов */}
        <div className="col-span-1 flex items-center justify-center">
          <div className="text-center">
            <div className="text-lg font-bold text-purple-400">{item.stocks.length}</div>
            <div className="text-xs text-white/60">активных</div>
          </div>
        </div>

        {/* Характеристики (5 колонок) */}
        <div className="col-span-5 flex items-center">
          <div className="space-y-1 w-full">
            {keyCharacteristics.map((char, index) => (
              <div key={index} className="flex justify-between text-xs">
                <span className="text-white/60 truncate w-1/2">{char.name}:</span>
                <span className="text-white truncate w-1/2 text-right">
                  {Array.isArray(char.value) ? char.value.join(', ') : String(char.value)}
                </span>
              </div>
            ))}
            {item.subjectName && (
              <div className="flex justify-between text-xs">
                <span className="text-white/60">Категория:</span>
                <span className="text-blue-300 truncate text-right">{item.subjectName}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Города в модулях */}
      <div className="grid grid-cols-12 gap-4 p-3 bg-white/[0.02] border-l-2 border-blue-400/30">
        <div className="col-span-12 flex flex-wrap gap-3">
          {item.stocks.map((stock, stockIndex) => (
            <div
              key={`${stock.warehouseId}-${stockIndex}`}
              className="bg-white/10 rounded-lg px-3 py-2 border border-white/20 hover:border-white/30 transition-colors"
            >
              {/* Название города */}
              <div className="text-white text-sm font-medium mb-1">{stock.warehouseName}</div>

              {/* Цифры */}
              <div className="flex items-center gap-3 text-xs">
                <div className="text-center">
                  <div className={`font-bold ${stock.quantity > 0 ? 'text-green-400' : 'text-white/30'}`}>
                    {stock.quantity}
                  </div>
                  <div className="text-white/50">остаток</div>
                </div>

                {(stock.inWayToClient > 0 || stock.inWayFromClient > 0) && (
                  <>
                    <div className="w-px h-6 bg-white/20" />

                    {stock.inWayToClient > 0 && (
                      <div className="text-center">
                        <div className="font-bold text-orange-400">{stock.inWayToClient}</div>
                        <div className="text-white/50">к клиенту</div>
                      </div>
                    )}

                    {stock.inWayFromClient > 0 && (
                      <div className="text-center">
                        <div className="font-bold text-red-400">{stock.inWayFromClient}</div>
                        <div className="text-white/50">от клиента</div>
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
