"use client"

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

interface FavoriteItem {
  id: number;
  title: string;
  price: number;
  image?: string;
}

export function FavoriteItems() {
  const { items, removeFromFavorites } = useFavorites()
  const { addToCart, removeFromCart, items: cartItems } = useCart()

  const handleToggleCart = (item: FavoriteItem) => {
    const isItemInCart = cartItems.some(cartItem => cartItem.id === item.id)
    if (isItemInCart) {
      removeFromCart(item.id)
    } else {
      addToCart({
        id: item.id,
        title: item.title,
        price: item.price,
      })
    }
  }

  if (items.length === 0) {
    return (
      <div className="text-center py-12">
        <h2 className="text-2xl font-semibold mb-4">Избранное</h2>
        <p className="text-gray-500">У вас пока нет избранных товаров</p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      <h2 className="text-2xl font-semibold mb-4">Избранное</h2>
      {items.map((item) => {
        const isItemInCart = cartItems.some(cartItem => cartItem.id === item.id)
        return (
          <div key={item.id} className="flex gap-4 p-4 bg-white rounded-lg">
            <Image
              src={item.image || "/placeholder.svg"}
              alt={item.title}
              width={100}
              height={100}
              className="object-cover"
            />
            <div className="flex-1">
              <h3 className="font-medium">{item.title}</h3>
              <div className="text-lg font-bold mt-2">{item.price} ₽</div>
              <div className="flex gap-4 mt-4">
                <Button 
                  onClick={() => handleToggleCart(item)}
                  variant={isItemInCart ? "outline" : "default"}
                >
                  {isItemInCart ? (
                    <>
                      <Check className="mr-2 h-4 w-4" /> Убрать из корзины
                    </>
                  ) : (
                    <>
                      <ShoppingCart className="mr-2 h-4 w-4" /> В корзину
                    </>
                  )}
                </Button>
                <Button variant="outline" size="icon" onClick={() => removeFromFavorites(item.id)}>
                  <Trash className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        )
      })}
    </div>
  )
}

