/**
 * БЛОК ТОВАРОВ В ПОСТАВКЕ
 *
 * Выделен из direct-supply-creation.tsx
 * Управляет списком товаров в поставке с настройками количества и цены
 */

'use client'

import { Package, X, Calculator } from 'lucide-react'
import React from 'react'

import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import type { SupplyItemsBlockProps } from '../types/direct-supply.types'

export const SupplyItemsBlock = React.memo(function SupplyItemsBlock({
  supplyItems,
  onUpdateQuantity,
  onUpdatePrice,
  onRemoveItem,
}: SupplyItemsBlockProps) {
  // Функция для расчета объема одного товара в м³
  const calculateItemVolume = (card: { dimensions?: { length: number; width: number; height: number } }): number => {
    if (!card.dimensions) return 0

    const { length, width, height } = card.dimensions
    if (!length || !width || !height || length <= 0 || width <= 0 || height <= 0) {
      return 0
    }

    return (length / 100) * (width / 100) * (height / 100)
  }

  // Расчет общего объема
  const getTotalVolume = (): number => {
    return supplyItems.reduce((totalVolume, item) => {
      const itemVolume = calculateItemVolume(item.card)
      return totalVolume + itemVolume * item.quantity
    }, 0)
  }

  if (supplyItems.length === 0) {
    return (
      <Card className="bg-white/10 backdrop-blur border-white/20 p-6 flex-1 flex flex-col min-h-0">
        <div className="flex items-center justify-between mb-4 flex-shrink-0">
          <h3 className="text-white font-semibold text-lg">Товары в поставке</h3>
          <span className="text-white/60 text-sm">0 товаров</span>
        </div>

        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <div className="w-16 h-16 bg-gradient-to-br from-purple-500/20 to-blue-500/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <Package className="h-8 w-8 text-white/40" />
            </div>
            <h3 className="text-white/80 font-medium text-base mb-2">Поставка пуста</h3>
            <p className="text-white/50 text-sm">Добавьте товары из каталога выше</p>
          </div>
        </div>
      </Card>
    )
  }

  return (
    <Card className="bg-white/10 backdrop-blur border-white/20 p-4 flex-1 flex flex-col min-h-0">
      <div className="flex items-center justify-between mb-4 flex-shrink-0">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-gradient-to-r from-green-500 to-emerald-500 rounded-lg flex items-center justify-center">
            <Calculator className="h-4 w-4 text-white" />
          </div>
          <div>
            <h3 className="text-white font-semibold text-base">Товары в поставке</h3>
            <p className="text-white/60 text-xs">{supplyItems.length} товаров</p>
          </div>
        </div>

        {supplyItems.length > 0 && (
          <div className="text-right">
            <p className="text-emerald-400 text-sm font-medium">∑ {getTotalVolume().toFixed(4)} м³</p>
            <p className="text-white/60 text-xs">общий объем</p>
          </div>
        )}
      </div>

      <div className="flex-1 overflow-y-auto space-y-2 min-h-0">
        {supplyItems.map((item) => (
          <Card key={item.card.nmID} className="bg-white/5 border-white/10 p-3">
            {/* Заголовок товара */}
            <div className="flex items-start justify-between mb-3">
              <div className="flex-1 min-w-0">
                <h4 className="text-white font-medium text-sm line-clamp-2 mb-1">{item.card.title}</h4>
                <div className="flex items-center space-x-3 text-xs text-white/60">
                  <span>WB: {item.card.nmID}</span>
                  {item.card.vendorCode && <span>Арт: {item.card.vendorCode}</span>}
                  {calculateItemVolume(item.card) > 0 && (
                    <span className="text-blue-400">{calculateItemVolume(item.card).toFixed(6)} м³/шт</span>
                  )}
                </div>
              </div>

              <Button
                onClick={() => onRemoveItem(item.card.nmID)}
                variant="ghost"
                size="sm"
                className="text-red-400 hover:text-red-300 hover:bg-red-500/10 ml-2 flex-shrink-0"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            {/* Настройки количества и цены */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
              {/* Количество */}
              <div>
                <label className="text-white/70 text-xs mb-1 block">Количество</label>
                <Input
                  type="number"
                  min="1"
                  value={item.quantity}
                  onChange={(e) => onUpdateQuantity(item.card.nmID, parseInt(e.target.value) || 0)}
                  className="h-8 bg-white/10 border-white/20 text-white text-sm"
                  placeholder="0"
                />
              </div>

              {/* Цена */}
              <div>
                <label className="text-white/70 text-xs mb-1 block">Цена</label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  value={item.pricePerUnit}
                  onChange={(e) => onUpdatePrice(item.card.nmID, parseFloat(e.target.value) || 0, item.priceType)}
                  className="h-8 bg-white/10 border-white/20 text-white text-sm"
                  placeholder="0.00"
                />
              </div>

              {/* Тип цены */}
              <div>
                <label className="text-white/70 text-xs mb-1 block">Тип цены</label>
                <Select
                  value={item.priceType}
                  onValueChange={(value: 'perUnit' | 'total') =>
                    onUpdatePrice(item.card.nmID, item.pricePerUnit, value)
                  }
                >
                  <SelectTrigger className="h-8 bg-white/10 border-white/20 text-white text-sm">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="perUnit">За штуку</SelectItem>
                    <SelectItem value="total">За всё количество</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Итоговая стоимость */}
            <div className="mt-2 pt-2 border-t border-white/10">
              <div className="flex justify-between items-center">
                <span className="text-white/60 text-xs">Итого за товар:</span>
                <span className="text-emerald-400 font-semibold text-sm">
                  {item.totalPrice.toLocaleString('ru-RU')} ₽
                </span>
              </div>
              {calculateItemVolume(item.card) > 0 && (
                <div className="flex justify-between items-center mt-1">
                  <span className="text-white/60 text-xs">Объем товара:</span>
                  <span className="text-blue-400 text-xs">
                    {(calculateItemVolume(item.card) * item.quantity).toFixed(6)} м³
                  </span>
                </div>
              )}
            </div>
          </Card>
        ))}
      </div>

      {/* Общая информация */}
      <div className="mt-4 pt-4 border-t border-white/20 flex-shrink-0">
        <div className="bg-gradient-to-r from-emerald-500/10 to-green-500/10 rounded-lg p-3 border border-emerald-400/20">
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div className="space-y-1">
              <div className="flex justify-between">
                <span className="text-white/70">Товаров:</span>
                <span className="text-white">{supplyItems.length}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-white/70">Общее количество:</span>
                <span className="text-white">{supplyItems.reduce((sum, item) => sum + item.quantity, 0)} шт</span>
              </div>
            </div>
            <div className="space-y-1">
              <div className="flex justify-between">
                <span className="text-white/70">Общий объем:</span>
                <span className="text-blue-400">{getTotalVolume().toFixed(4)} м³</span>
              </div>
              <div className="flex justify-between">
                <span className="text-white/70">Общая стоимость:</span>
                <span className="text-emerald-400 font-semibold">
                  {supplyItems.reduce((sum, item) => sum + item.totalPrice, 0).toLocaleString('ru-RU')} ₽
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Card>
  )
})
