'use client'

import { Package, Plus, Minus, X, Settings, ShoppingCart } from 'lucide-react'
import Image from 'next/image'
import React, { useState } from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'

interface GoodsProduct {
  id: string
  name: string
  description?: string
  price: number
  category?: { name: string }
  images: string[]
  mainImage?: string
  sku: string
  organization: {
    id: string
    name: string
  }
  stock?: number
  unit?: string
  weight?: number
  dimensions?: {
    length: number
    width: number
    height: number
  }
}

interface ProductParameter {
  name: string
  value: string
}

interface AddGoodsModalProps {
  product: GoodsProduct | null
  isOpen: boolean
  onClose: () => void
  onAdd: (
    product: GoodsProduct,
    quantity: number,
    additionalData: {
      completeness?: string
      recipe?: string
      specialRequirements?: string
      parameters?: ProductParameter[]
      customPrice?: number
    },
  ) => void
}

export function AddGoodsModal({ product, isOpen, onClose, onAdd }: AddGoodsModalProps) {
  const [quantity, setQuantity] = useState(1)
  const [completeness, setCompleteness] = useState('')
  const [recipe, setRecipe] = useState('')
  const [specialRequirements, setSpecialRequirements] = useState('')
  const [customPrice, setCustomPrice] = useState('')
  const [parameters, setParameters] = useState<ProductParameter[]>([])
  const [newParameterName, setNewParameterName] = useState('')
  const [newParameterValue, setNewParameterValue] = useState('')

  // Сброс формы при закрытии
  const handleClose = () => {
    setQuantity(1)
    setCompleteness('')
    setRecipe('')
    setSpecialRequirements('')
    setCustomPrice('')
    setParameters([])
    setNewParameterName('')
    setNewParameterValue('')
    onClose()
  }

  // Добавление параметра
  const addParameter = () => {
    if (newParameterName.trim() && newParameterValue.trim()) {
      setParameters((prev) => [...prev, { name: newParameterName.trim(), value: newParameterValue.trim() }])
      setNewParameterName('')
      setNewParameterValue('')
    }
  }

  // Удаление параметра
  const removeParameter = (index: number) => {
    setParameters((prev) => prev.filter((_, i) => i !== index))
  }

  // Обработка добавления в корзину
  const handleAdd = () => {
    if (!product) return

    // Проверка остатков согласно rules2.md 9.7.9
    if (product.stock !== undefined && quantity > product.stock) {
      return // Ошибка будет показана в родительском компоненте
    }

    const finalPrice = customPrice ? parseFloat(customPrice) : product.price

    onAdd(product, quantity, {
      completeness: completeness.trim() || undefined,
      recipe: recipe.trim() || undefined,
      specialRequirements: specialRequirements.trim() || undefined,
      parameters: parameters.length > 0 ? parameters : undefined,
      customPrice: finalPrice !== product.price ? finalPrice : undefined,
    })

    handleClose()
  }

  if (!product) return null

  const isStockAvailable = product.stock === undefined || quantity <= product.stock
  const totalPrice = (customPrice ? parseFloat(customPrice) || product.price : product.price) * quantity

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[600px] bg-white/10 backdrop-blur-xl border border-white/20 text-white">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-xl">
            <Package className="h-6 w-6 text-white/80" />
            Добавить товар в корзину
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6 max-h-[70vh] overflow-y-auto pr-2">
          {/* Информация о товаре */}
          <div className="bg-white/5 border border-white/10 rounded-lg p-4">
            <div className="flex gap-4">
              {product.mainImage && (
                <div className="w-24 h-24 rounded-lg overflow-hidden bg-white/5 flex-shrink-0">
                  <Image
                    src={product.mainImage}
                    alt={product.name}
                    width={96}
                    height={96}
                    className="w-full h-full object-cover"
                  />
                </div>
              )}

              <div className="flex-1 space-y-2">
                <h3 className="text-white font-semibold text-lg">{product.name}</h3>
                <p className="text-white/60 text-sm">Артикул: {product.sku}</p>
                {product.category && (
                  <Badge className="bg-white/10 text-white/70 text-xs">{product.category.name}</Badge>
                )}
                <div className="flex items-center justify-between">
                  <p className="text-white font-medium">
                    Цена: {product.price.toLocaleString('ru-RU')} ₽ за {product.unit || 'шт'}
                  </p>
                  {product.stock !== undefined && (
                    <p className="text-white/60 text-sm">
                      В наличии: {product.stock} {product.unit || 'шт'}
                    </p>
                  )}
                </div>
              </div>
            </div>

            {product.description && (
              <p className="text-white/70 text-sm mt-3 pt-3 border-t border-white/10">{product.description}</p>
            )}
          </div>

          {/* Основные поля */}
          <div className="grid grid-cols-2 gap-4">
            {/* Количество */}
            <div>
              <Label className="text-white/70 text-sm mb-2 block">Количество *</Label>
              <div className="flex items-center gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => setQuantity(Math.max(1, quantity - 1))}
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  <Minus className="h-3 w-3" />
                </Button>
                <Input
                  type="number"
                  min="1"
                  max={product.stock}
                  value={quantity}
                  onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
                  className="bg-white/10 border-white/20 text-white text-center w-20"
                />
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => setQuantity(product.stock ? Math.min(product.stock, quantity + 1) : quantity + 1)}
                  className="border-white/20 text-white hover:bg-white/10"
                  disabled={product.stock !== undefined && quantity >= product.stock}
                >
                  <Plus className="h-3 w-3" />
                </Button>
              </div>
              {!isStockAvailable && <p className="text-red-400 text-xs mt-1">Недостаточно товара на складе</p>}
            </div>

            {/* Договорная цена */}
            <div>
              <Label className="text-white/70 text-sm mb-2 block">Договорная цена (₽)</Label>
              <Input
                type="number"
                min="0"
                step="0.01"
                value={customPrice}
                onChange={(e) => setCustomPrice(e.target.value)}
                placeholder={product.price.toString()}
                className="bg-white/10 border-white/20 text-white"
              />
              <p className="text-white/40 text-xs mt-1">Оставьте пустым для использования базовой цены</p>
            </div>
          </div>

          {/* Комплектность согласно rules2.md 9.7.2 */}
          <div>
            <Label className="text-white/70 text-sm mb-2 block">Комплектность (если есть)</Label>
            <Textarea
              value={completeness}
              onChange={(e) => setCompleteness(e.target.value)}
              placeholder="Опишите состав комплекта, если товар продается набором..."
              className="bg-white/10 border-white/20 text-white placeholder-white/40 resize-none"
              rows={2}
            />
          </div>

          {/* Рецептура/состав согласно rules2.md 9.7.2 */}
          <div>
            <Label className="text-white/70 text-sm mb-2 block">Рецептура/состав</Label>
            <Textarea
              value={recipe}
              onChange={(e) => setRecipe(e.target.value)}
              placeholder="Дополнительные требования к составу, рецептуре или производству..."
              className="bg-white/10 border-white/20 text-white placeholder-white/40 resize-none"
              rows={3}
            />
          </div>

          {/* Особые требования */}
          <div>
            <Label className="text-white/70 text-sm mb-2 block">Особые требования к товару</Label>
            <Textarea
              value={specialRequirements}
              onChange={(e) => setSpecialRequirements(e.target.value)}
              placeholder="Особые требования к качеству, упаковке, срокам и т.д..."
              className="bg-white/10 border-white/20 text-white placeholder-white/40 resize-none"
              rows={2}
            />
          </div>

          {/* Параметры товара согласно rules2.md 9.7.5 */}
          <div>
            <Label className="text-white/70 text-sm mb-2 block flex items-center gap-2">
              <Settings className="h-4 w-4" />
              Параметры товара
            </Label>

            {/* Существующие параметры */}
            {parameters.length > 0 && (
              <div className="space-y-2 mb-3">
                {parameters.map((param, index) => (
                  <div key={index} className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg p-2">
                    <span className="text-white/80 text-sm font-medium">{param.name}:</span>
                    <span className="text-white text-sm">{param.value}</span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeParameter(index)}
                      className="text-red-400 hover:text-red-300 hover:bg-red-500/10 ml-auto p-1 h-auto"
                    >
                      <X className="h-3 w-3" />
                    </Button>
                  </div>
                ))}
              </div>
            )}

            {/* Добавление нового параметра */}
            <div className="flex gap-2">
              <Input
                value={newParameterName}
                onChange={(e) => setNewParameterName(e.target.value)}
                placeholder="Название параметра (цвет, размер...)"
                className="bg-white/10 border-white/20 text-white placeholder-white/40 flex-1"
              />
              <Input
                value={newParameterValue}
                onChange={(e) => setNewParameterValue(e.target.value)}
                placeholder="Значение"
                className="bg-white/10 border-white/20 text-white placeholder-white/40 flex-1"
              />
              <Button
                type="button"
                onClick={addParameter}
                disabled={!newParameterName.trim() || !newParameterValue.trim()}
                className="bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 border-blue-500/30"
              >
                <Plus className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Итоговая стоимость */}
          <div className="bg-white/5 border border-white/10 rounded-lg p-4">
            <div className="flex justify-between items-center">
              <span className="text-white/70">Итоговая стоимость:</span>
              <span className="text-green-400 font-bold text-lg">{totalPrice.toLocaleString('ru-RU')} ₽</span>
            </div>
            {customPrice && parseFloat(customPrice) !== product.price && (
              <p className="text-yellow-400 text-xs mt-1">
                Используется договорная цена: {parseFloat(customPrice).toLocaleString('ru-RU')} ₽ за{' '}
                {product.unit || 'шт'}
              </p>
            )}
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleClose} className="border-white/20 text-white hover:bg-white/10">
            Отмена
          </Button>
          <Button
            onClick={handleAdd}
            disabled={!isStockAvailable || quantity < 1}
            className="bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600 text-white"
          >
            <ShoppingCart className="h-4 w-4 mr-2" />
            Добавить в корзину
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
