import React, { useState } from "react";
import { useCart } from "@/contexts/CartContext";
import { toast } from "react-hot-toast";
import CartIcon from "../CartIcon";
interface ProductBuyBlockProps {
offer?: any;
}
const ProductBuyBlock = ({ offer }: ProductBuyBlockProps) => {
const [quantity, setQuantity] = useState(1);
const { addItem } = useCart();
if (!offer) {
return (
);
}
const handleQuantityChange = (delta: number) => {
const newQuantity = Math.max(1, Math.min(offer.quantity || 999, quantity + delta));
setQuantity(newQuantity);
};
// Обработчик добавления в корзину
const handleAddToCart = async (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
try {
if (!offer.price || offer.price <= 0) {
toast.error('Цена товара не найдена');
return;
}
// Добавляем товар в корзину
const result = await addItem({
productId: offer.id ? String(offer.id) : undefined,
offerKey: offer.offerKey || undefined,
name: offer.name || `${offer.brand} ${offer.articleNumber}`,
description: offer.name || `${offer.brand} ${offer.articleNumber}`,
price: offer.price,
currency: 'RUB',
quantity: quantity,
stock: offer.quantity, // передаем информацию о наличии
image: offer.image || undefined,
brand: offer.brand,
article: offer.articleNumber,
supplier: offer.supplier || (offer.type === 'external' ? 'AutoEuro' : 'Внутренний'),
deliveryTime: offer.deliveryTime ? String(offer.deliveryTime) + ' дней' : '1 день',
isExternal: offer.type === 'external'
});
if (result.success) {
// Показываем успешный тоастер
toast.success(
Товар добавлен в корзину!
{offer.name || `${offer.brand} ${offer.articleNumber}`}
,
{
duration: 3000,
icon: ,
}
);
} else {
// Показываем ошибку
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
}
} catch (error) {
console.error('Ошибка добавления в корзину:', error);
toast.error('Ошибка при добавлении товара в корзину');
}
};
const totalPrice = offer.price * quantity;
return (
{offer.quantity || 0} шт
{totalPrice.toLocaleString('ru-RU')} ₽
handleQuantityChange(-1)}>
handleQuantityChange(1)}>
e.currentTarget.style.transform = 'scale(1.05)'}
onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
>
);
};
export default ProductBuyBlock;