"use client"

import Image from "next/image"
import Link from "next/link"
import { Heart, ShoppingCart } from 'lucide-react'
import { Button } from "./ui/button"
import { useCart } from "@/contexts/cart-context"
import { useFavorites } from "@/contexts/favorites-context"

interface ProductCardProps {
  product: {
    id: number
    title: string
    price: number
    image: string
  }
}

export function ProductCard({ product }: ProductCardProps) {
  const { addToCart, removeFromCart } = useCart()
  const { addToFavorites, removeFromFavorites, isFavorite } = useFavorites()

  const handleAddToCart = (e: React.MouseEvent) => {
    e.preventDefault()
    addToCart({
      id: product.id,
      title: product.title,
      price: product.price,
    })
  }

  const handleRemoveFromCart = (e: React.MouseEvent) => {
    e.preventDefault()
    removeFromCart(product.id)
  }

  const handleToggleFavorite = (e: React.MouseEvent) => {
    e.preventDefault()
    if (isFavorite(product.id)) {
      removeFromFavorites(product.id)
    } else {
      addToFavorites({
        id: product.id,
        title: product.title,
        price: product.price,
      })
    }
  }

  return (
    <Link href={`/product/${product.id}`} className="group relative bg-white rounded-lg p-2 transition-shadow hover:shadow-lg block">
      <div className="relative aspect-square mb-2">
        <Image
          src={product.image}
          alt={product.title}
          fill
          className="object-cover rounded-lg"
        />
        <Button
          variant="ghost"
          size="icon"
          className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
          onClick={handleToggleFavorite}
        >
          <Heart className={`h-5 w-5 ${isFavorite(product.id) ? 'fill-red-500 text-red-500' : ''}`} />
        </Button>
      </div>
      <div className="space-y-2">
        <span className="text-xl font-bold">{product.price} ₽</span>
        <h3 className="text-sm line-clamp-2">{product.title}</h3>
        <div className="flex gap-2">
          <Button onClick={handleAddToCart} className="flex-1">
            <ShoppingCart className="mr-2 h-4 w-4" /> В корзину
          </Button>
          <Button onClick={handleRemoveFromCart} variant="outline" size="icon">
            -
          </Button>
        </div>
      </div>
    </Link>
  )
}

