'use client'

import { useMutation } from '@apollo/client'
import { Edit3, Trash2, Package, Eye, EyeOff } from 'lucide-react'
import Image from 'next/image'
import { useState } from 'react'
import { toast } from 'sonner'

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { DELETE_PRODUCT } from '@/graphql/mutations'

interface Product {
  id: string
  name: string
  article: string
  description: string
  price: number
  pricePerSet?: number
  quantity: number
  setQuantity?: number
  ordered?: number
  inTransit?: number
  stock?: number
  sold?: number
  type: 'PRODUCT' | 'CONSUMABLE'
  category: { id: string; name: string } | null
  brand: string
  color: string
  size: string
  weight: number
  dimensions: string
  material: string
  images: string[]
  mainImage: string
  isActive: boolean
  createdAt: string
  updatedAt: string
  organization: { id: string; market?: string }
}

interface ProductCardProps {
  product: Product
  onEdit: (product: Product) => void
  onDeleted: () => void
}

// Функция для отображения бэйджа рынка согласно правилам системы
const getMarketBadge = (market?: string) => {
  if (!market) return null
  
  const marketStyles = {
    sadovod: 'bg-green-500/20 text-green-300 border-green-500/30',
    'tyak-moscow': 'bg-blue-500/20 text-blue-300 border-blue-500/30',
  }
  
  const marketLabels = {
    sadovod: 'Садовод',
    'tyak-moscow': 'ТЯК Москва',
  }
  
  const style = marketStyles[market as keyof typeof marketStyles] || 'bg-gray-500/20 text-gray-300 border-gray-500/30'
  const label = marketLabels[market as keyof typeof marketLabels] || market
  
  return (
    <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium border ${style}`}>
      {label}
    </span>
  )
}

export function ProductCard({ product, onEdit, onDeleted }: ProductCardProps) {
  const [deleteProduct, { loading: deleting }] = useMutation(DELETE_PRODUCT)
  const [imageDialogOpen, setImageDialogOpen] = useState(false)

  const handleDelete = async () => {
    try {
      await deleteProduct({
        variables: { id: product.id },
      })
      toast.success('Товар успешно удален')
      onDeleted()
    } catch (error) {
      console.error('Error deleting product:', error)
      toast.error('Ошибка при удалении товара')
    }
  }

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
    }).format(price)
  }

  const getStatusColor = () => {
    const stock = product.stock || product.quantity || 0
    if (!product.isActive) return 'bg-gray-500/20 text-gray-300 border-gray-400/30'
    if (stock === 0) return 'bg-red-500/20 text-red-300 border-red-400/30'
    if (stock < 10) return 'bg-yellow-500/20 text-yellow-300 border-yellow-400/30'
    return 'bg-green-500/20 text-green-300 border-green-400/30'
  }

  const getStatusText = () => {
    const stock = product.stock || product.quantity || 0
    if (!product.isActive) return 'Неактивен'
    if (stock === 0) return 'Нет в наличии'
    if (stock < 10) return 'Мало на складе'
    return 'В наличии'
  }

  const getStockQuantity = () => {
    return product.stock || product.quantity || 0
  }

  return (
    <Card className="glass-card group relative overflow-hidden transition-all duration-300">
      {/* Изображение товара */}
      <div className="relative h-48 bg-white/5 overflow-hidden flex items-center justify-center">
        {product.mainImage || product.images[0] ? (
          <Dialog open={imageDialogOpen} onOpenChange={setImageDialogOpen}>
            <DialogTrigger asChild>
              <div className="cursor-zoom-in w-full h-full flex items-center justify-center">
                <Image
                  src={product.mainImage || product.images[0]}
                  alt={product.name}
                  width={300}
                  height={200}
                  className="w-full h-full object-contain"
                />
              </div>
            </DialogTrigger>
            <DialogContent className="glass-card max-w-4xl max-h-[90vh] p-2">
              <DialogHeader>
                <DialogTitle className="text-white">{product.name}</DialogTitle>
              </DialogHeader>
              <div className="flex items-center justify-center p-4">
                <Image
                  src={product.mainImage || product.images[0]}
                  alt={product.name}
                  width={800}
                  height={600}
                  className="max-w-full max-h-[70vh] object-contain rounded-lg"
                />
              </div>
            </DialogContent>
          </Dialog>
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Package className="h-16 w-16 text-white/30" />
          </div>
        )}

        {/* Статус товара */}
        <div className="absolute top-2 left-2">
          <Badge className={`text-xs px-2 py-1 ${getStatusColor()}`}>{getStatusText()}</Badge>
        </div>

        {/* Индикатор активности */}
        <div className="absolute top-2 right-2">
          {product.isActive ? <Eye className="h-4 w-4 text-green-300" /> : <EyeOff className="h-4 w-4 text-gray-400" />}
        </div>

        {/* Кнопки управления */}
        <div className="absolute bottom-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
          <Button
            size="sm"
            variant="outline"
            onClick={() => onEdit(product)}
            className="p-1 h-7 w-7 bg-white/20 border-white/30 hover:bg-white/30 backdrop-blur"
          >
            <Edit3 className="h-3 w-3 text-white" />
          </Button>

          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button
                size="sm"
                variant="outline"
                className="p-1 h-7 w-7 bg-red-500/20 border-red-400/30 hover:bg-red-500/30 backdrop-blur"
              >
                <Trash2 className="h-3 w-3 text-white" />
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent className="glass-card border-white/10">
              <AlertDialogHeader>
                <AlertDialogTitle className="text-white">Удалить товар?</AlertDialogTitle>
                <AlertDialogDescription className="text-white/70">
                  Вы уверены, что хотите удалить товар &quot;{product.name}&quot;? Это действие нельзя отменить.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel className="glass-secondary text-white hover:text-white">Отмена</AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleDelete}
                  disabled={deleting}
                  className="bg-red-600 hover:bg-red-700 text-white"
                >
                  {deleting ? 'Удаление...' : 'Удалить'}
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </div>

      {/* Информация о товаре */}
      <div className="p-4 space-y-3">
        {/* Название и артикул */}
        <div>
          <h3 className="text-white font-medium text-sm line-clamp-2 leading-tight">{product.name}</h3>
          <p className="text-white/60 text-xs mt-1">Арт. {product.article}</p>
        </div>

        {/* Цена и количество */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-white font-semibold">{formatPrice(product.price)}</div>
              {product.pricePerSet && (
                <div className="text-white/60 text-xs">Комплект: {formatPrice(product.pricePerSet)}</div>
              )}
            </div>
            <div className="text-right">
              <div className="text-white/70 text-sm">{getStockQuantity()} шт.</div>
              {product.setQuantity && <div className="text-white/60 text-xs">{product.setQuantity} компл.</div>}
            </div>
          </div>

          {/* Учет движения */}
          <div className="grid grid-cols-3 gap-2 text-xs">
            <div className="text-center bg-yellow-500/10 rounded p-1">
              <div className="text-yellow-300 font-medium">{product.ordered || 0}</div>
              <div className="text-yellow-300/70">Заказано</div>
            </div>
            <div className="text-center bg-purple-500/10 rounded p-1">
              <div className="text-purple-300 font-medium">{product.inTransit || 0}</div>
              <div className="text-purple-300/70">В пути</div>
            </div>
            <div className="text-center bg-green-500/10 rounded p-1">
              <div className="text-green-300 font-medium">{product.sold || 0}</div>
              <div className="text-green-300/70">Продано</div>
            </div>
          </div>
        </div>

        {/* Дополнительная информация */}
        <div className="space-y-1">
          <div className="flex items-center gap-2 flex-wrap">
            {/* Тип товара */}
            <Badge
              variant="outline"
              className={`text-xs ${
                product.type === 'PRODUCT'
                  ? 'bg-blue-500/20 text-blue-300 border-blue-400/30'
                  : 'bg-orange-500/20 text-orange-300 border-orange-400/30'
              }`}
            >
              {product.type === 'PRODUCT' ? 'Товар' : 'Расходник'}
            </Badge>

            {/* Рынок */}
            {getMarketBadge(product.organization?.market)}

            {/* Категория */}
            {product.category && (
              <Badge variant="outline" className="glass-secondary text-white/60 border-white/20 text-xs">
                {product.category.name}
              </Badge>
            )}
          </div>

          <div className="flex flex-wrap gap-1">
            {product.brand && (
              <span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">{product.brand}</span>
            )}
            {product.color && (
              <span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">{product.color}</span>
            )}
            {product.size && (
              <span className="text-white/50 text-xs bg-white/10 px-2 py-1 rounded">{product.size}</span>
            )}
          </div>
        </div>

        {/* Описание (если есть) */}
        {product.description && (
          <p className="text-white/60 text-xs line-clamp-2 leading-relaxed">{product.description}</p>
        )}
      </div>

      {/* Эффект градиента при наведении */}
      <div className="absolute inset-0 bg-gradient-to-t from-purple-600/0 via-transparent to-transparent opacity-0 group-hover:opacity-20 transition-opacity duration-300 pointer-events-none" />
    </Card>
  )
}
