"use client"

import { useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { 
  ShoppingCart,
  Eye,
  ChevronLeft,
  ChevronRight,
  Heart
} from 'lucide-react'
import { OrganizationAvatar } from './organization-avatar'
import { Input } from '@/components/ui/input'
import Image from 'next/image'
import { useMutation, useQuery } from '@apollo/client'
import { ADD_TO_CART, ADD_TO_FAVORITES, REMOVE_FROM_FAVORITES } from '@/graphql/mutations'
import { GET_MY_CART, GET_MY_FAVORITES } from '@/graphql/queries'
import { toast } from 'sonner'

interface Product {
  id: string
  name: string
  article: string
  description?: string
  price: number
  quantity: number
  category?: { id: string; name: string }
  brand?: string
  color?: string
  size?: string
  weight?: number
  dimensions?: string
  material?: string
  images: string[]
  mainImage?: string
  isActive: boolean
  createdAt: string
  organization: {
    id: string
    inn: string
    name?: string
    fullName?: string
    type: string
    address?: string
    phones?: Array<{ value: string }>
    emails?: Array<{ value: string }>
    users?: Array<{ id: string, avatar?: string, managerName?: string }>
  }
}

interface ProductCardProps {
  product: Product
}

export function ProductCard({ product }: ProductCardProps) {
  const [currentImageIndex, setCurrentImageIndex] = useState(0)
  const [isImageDialogOpen, setIsImageDialogOpen] = useState(false)
  const [quantity, setQuantity] = useState(1)

  // Запрос избранного для проверки статуса
  const { data: favoritesData } = useQuery(GET_MY_FAVORITES)
  const favorites = favoritesData?.myFavorites || []
  const isFavorite = favorites.some((fav: Product) => fav.id === product.id)

  const [addToCart, { loading: addingToCart }] = useMutation(ADD_TO_CART, {
    refetchQueries: [{ query: GET_MY_CART }],
    onCompleted: (data) => {
      if (data.addToCart.success) {
        toast.success(data.addToCart.message)
        setQuantity(1) // Сбрасываем количество после добавления
      } else {
        toast.error(data.addToCart.message)
      }
    },
    onError: (error) => {
      toast.error('Ошибка при добавлении в заявки')
      console.error('Error adding to cart:', error)
    }
  })

  const [addToFavorites, { loading: addingToFavorites }] = useMutation(ADD_TO_FAVORITES, {
    refetchQueries: [{ query: GET_MY_FAVORITES }],
    onCompleted: (data) => {
      if (data.addToFavorites.success) {
        toast.success(data.addToFavorites.message)
      } else {
        toast.error(data.addToFavorites.message)
      }
    },
    onError: (error) => {
      toast.error('Ошибка при добавлении в избранное')
      console.error('Error adding to favorites:', error)
    }
  })

  const [removeFromFavorites, { loading: removingFromFavorites }] = useMutation(REMOVE_FROM_FAVORITES, {
    refetchQueries: [{ query: GET_MY_FAVORITES }],
    onCompleted: (data) => {
      if (data.removeFromFavorites.success) {
        toast.success(data.removeFromFavorites.message)
      } else {
        toast.error(data.removeFromFavorites.message)
      }
    },
    onError: (error) => {
      toast.error('Ошибка при удалении из избранного')
      console.error('Error removing from favorites:', error)
    }
  })

  const displayPrice = new Intl.NumberFormat('ru-RU', {
    style: 'currency',
    currency: 'RUB'
  }).format(product.price)

  const displayName = product.organization.name || product.organization.fullName || 'Неизвестная организация'
  const images = product.images.length > 0 ? product.images : [product.mainImage].filter(Boolean)
  const hasMultipleImages = images.length > 1

  const handleAddToCart = async () => {
    try {
      await addToCart({
        variables: {
          productId: product.id,
          quantity: quantity
        }
      })
    } catch (error) {
      console.error('Error adding to cart:', error)
    }
  }

  const handleToggleFavorite = async () => {
    try {
      if (isFavorite) {
        await removeFromFavorites({
          variables: { productId: product.id }
        })
      } else {
        await addToFavorites({
          variables: { productId: product.id }
        })
      }
    } catch (error) {
      console.error('Error toggling favorite:', error)
    }
  }

  const nextImage = () => {
    setCurrentImageIndex((prev) => (prev + 1) % images.length)
  }

  const prevImage = () => {
    setCurrentImageIndex((prev) => (prev - 1 + images.length) % images.length)
  }

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

  const stockStatus = getStockStatus()
  const canAddToCart = product.quantity > 0 && product.isActive

  return (
    <div className="glass-card p-3 hover:bg-white/10 transition-all duration-300 group">
      {/* Изображения товара */}
      <div className="relative mb-3 aspect-video bg-white/5 rounded-lg overflow-hidden">
        {images.length > 0 ? (
          <>
            <Image
              src={images[currentImageIndex] || '/placeholder-product.png'}
              alt={product.name}
              fill
              className="object-cover cursor-pointer"
              onClick={() => setIsImageDialogOpen(true)}
            />
            
            {/* Навигация по изображениям */}
            {hasMultipleImages && (
              <>
                <button
                  onClick={prevImage}
                  className="absolute left-2 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <ChevronLeft className="h-4 w-4" />
                </button>
                <button
                  onClick={nextImage}
                  className="absolute right-2 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <ChevronRight className="h-4 w-4" />
                </button>
                
                {/* Индикаторы изображений */}
                <div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex space-x-1">
                  {images.map((_, index) => (
                    <div
                      key={index}
                      className={`w-2 h-2 rounded-full transition-all ${
                        index === currentImageIndex ? 'bg-white' : 'bg-white/50'
                      }`}
                    />
                  ))}
                </div>
              </>
            )}
            
            {/* Кнопка увеличения */}
            <button
              onClick={() => setIsImageDialogOpen(true)}
              className="absolute top-2 right-2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
            >
              <Eye className="h-4 w-4" />
            </button>
          </>
        ) : (
          <div className="absolute inset-0 flex items-center justify-center">
            <ShoppingCart className="h-8 w-8 text-white/20" />
          </div>
        )}
      </div>

      {/* Информация о товаре */}
      <div className="space-y-2">
        {/* Название и цена */}
        <div>
          <h3 className="font-semibold text-white text-sm mb-1 line-clamp-1">{product.name}</h3>
          <div className="flex items-center justify-between">
            <span className="text-base font-bold text-purple-300">{displayPrice}</span>
            <Badge className={`${stockStatus.color} text-xs`}>
              {stockStatus.text}
            </Badge>
          </div>
        </div>

        {/* Краткая информация */}
        <div className="flex items-center justify-between text-xs text-white/60">
          <span>Арт: {product.article}</span>
          {product.category && (
            <span className="bg-white/10 px-2 py-1 rounded text-xs">{product.category.name}</span>
          )}
        </div>

        {/* Информация о продавце */}
        <div className="border-t border-white/10 pt-2">
          <div className="flex items-center space-x-2">
            <OrganizationAvatar organization={product.organization} size="sm" />
            <div className="flex-1 min-w-0">
              <p className="font-medium text-white text-xs truncate">{displayName}</p>
              <p className="text-xs text-white/50">ИНН: {product.organization.inn}</p>
            </div>
          </div>
        </div>

        {/* Выбор количества и добавление в заявки */}
        {canAddToCart ? (
          <div className="space-y-2">
            {/* Выбор количества */}
            <div className="flex items-center justify-between">
              <span className="text-xs text-white/70">Количество:</span>
              <Input
                type="number"
                min="1"
                max={product.quantity}
                value={quantity}
                onChange={(e) => {
                  const value = parseInt(e.target.value) || 1
                  if (value >= 1 && value <= product.quantity) {
                    setQuantity(value)
                  }
                }}
                className="w-16 h-6 text-xs text-center glass-input text-white border-white/20"
              />
            </div>

            {/* Кнопки действий */}
            <div className="flex items-center space-x-2">
              {/* Кнопка добавления в заявки */}
              <Button 
                onClick={handleAddToCart}
                disabled={addingToCart}
                className="flex-1 h-8 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white border-0 text-xs"
              >
                <ShoppingCart className="h-3 w-3 mr-1" />
                {addingToCart ? 'Добавление...' : 'В заявки'}
              </Button>

              {/* Кнопка избранного */}
              <Button 
                onClick={handleToggleFavorite}
                disabled={addingToFavorites || removingFromFavorites}
                variant="outline"
                size="sm"
                className={`h-8 w-8 p-0 transition-all ${
                  isFavorite 
                    ? 'bg-red-500/20 border-red-500/30 text-red-400 hover:bg-red-500/30' 
                    : 'bg-white/5 border-white/20 text-white/60 hover:bg-red-500/20 hover:border-red-500/30 hover:text-red-400'
                }`}
              >
                <Heart className={`h-4 w-4 ${isFavorite ? 'fill-current' : ''}`} />
              </Button>
            </div>
          </div>
        ) : (
          <div className="flex items-center space-x-2">
            <Button 
              disabled
              className="flex-1 h-8 bg-gray-500/20 text-gray-400 border-0 text-xs cursor-not-allowed"
            >
              <ShoppingCart className="h-3 w-3 mr-1" />
              Недоступно
            </Button>

            {/* Кнопка избранного (всегда доступна) */}
            <Button 
              onClick={handleToggleFavorite}
              disabled={addingToFavorites || removingFromFavorites}
              variant="outline"
              size="sm"
              className={`h-8 w-8 p-0 transition-all ${
                isFavorite 
                  ? 'bg-red-500/20 border-red-500/30 text-red-400 hover:bg-red-500/30' 
                  : 'bg-white/5 border-white/20 text-white/60 hover:bg-red-500/20 hover:border-red-500/30 hover:text-red-400'
              }`}
            >
              <Heart className={`h-4 w-4 ${isFavorite ? 'fill-current' : ''}`} />
            </Button>
          </div>
        )}
      </div>

      {/* Диалог просмотра изображений */}
      <Dialog open={isImageDialogOpen} onOpenChange={setIsImageDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] bg-black/90 backdrop-blur-xl border border-white/20 p-0">
          <DialogHeader className="sr-only">
            <DialogTitle>Просмотр изображения товара {product.name}</DialogTitle>
          </DialogHeader>
          <div className="relative">
            {images.length > 0 && (
              <div className="relative aspect-square">
                <Image
                  src={images[currentImageIndex] || '/placeholder-product.png'}
                  alt={product.name}
                  fill
                  className="object-contain"
                />
                
                {hasMultipleImages && (
                  <>
                    <button
                      onClick={prevImage}
                      className="absolute left-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full"
                    >
                      <ChevronLeft className="h-6 w-6" />
                    </button>
                    <button
                      onClick={nextImage}
                      className="absolute right-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full"
                    >
                      <ChevronRight className="h-6 w-6" />
                    </button>
                  </>
                )}
                
                <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/50 px-3 py-1 rounded-full text-white text-sm">
                  {currentImageIndex + 1} из {images.length}
                </div>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
} 