import React, { useState } from 'react';
import {
Box,
Typography,
Paper,
List,
ListItem,
ListItemText,
Button,
TextField,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
CircularProgress
} from '@mui/material';
import authService from '../../../../services/authService';
import { useSnackbar } from "../../../../contexts/SnackbarContext";
const CartDetails = ({ cart, onClose, onUpdated, onDeleted }) => {
const [editMode, setEditMode] = useState(false);
const [totalPrice, setTotalPrice] = useState(cart?.attributes?.total_price || "");
const [cartItems, setCartItems] = useState(cart.relationships?.cartItems || cart.relationships?.cart_items || []);
const [loading, setLoading] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
const { showSnackbar } = useSnackbar();
if (!cart) return null;
const handleSaveAll = async () => {
setLoading(true);
const payload = {
data: {
type: "cart",
attributes: {
totalPrice: Number(totalPrice),
},
relationships: {
cartItems: cartItems.map(item => ({
attributes: {
quantity: Number(item.attributes.quantity),
},
relationships: {
product: {
data: {
id: item.relationships?.supplier_product?.id ||
item.relationships?.product?.data?.id
}
}
}
})),
},
},
};
try {
const result = await authService.updateCart(cart.id, payload);
if (result.success) {
onUpdated(result.data);
setEditMode(false);
} else {
// alert(result.message || 'Failed to update cart');
showSnackbar(result.message || "Failed to update cart", "error");
}
} catch (error) {
// alert('An error occurred while updating the cart');
showSnackbar("An error occurred while updating the cart", "error");
} finally {
setLoading(false);
}
};
const handleDeleteCart = async () => {
setDeleteLoading(true);
try {
const result = await authService.deleteCart(cart.id);
if (result.success) {
onDeleted(cart.id);
onClose();
} else {
// alert(result.message || 'Failed to delete cart');
showSnackbar(result.message || "Failed to update cart", "error");
}
} catch (error) {
// alert('An error occurred while deleting the cart');
showSnackbar("An error occurred while deleting the cart", "error");
} finally {
setDeleteLoading(false);
setOpenDeleteDialog(false);
}
};
const handleChangeQuantity = (itemId, newQuantity) => {
setCartItems(prev =>
prev.map(item =>
item.id === itemId
? { ...item, attributes: { ...item.attributes, quantity: newQuantity } }
: item
)
);
};
return (
<>
Cart #{cart.id} Details
{editMode ? (
<>
setTotalPrice(e.target.value)}
fullWidth
sx={{ mb: 2 }}
/>
Items:
{cartItems.map(item => (
handleChangeQuantity(item.id, Number(e.target.value))}
sx={{ width: '120px' }}
/>
}
/>
))}
>
) : (
<>
Total Price: {cart.attributes.total_price || cart.attributes.totalPrice}
Created At: {new Date(cart.attributes.createdAt).toLocaleString()}
Items:
{cartItems.map(item => (
))}
>
)}
{/* Delete Confirmation Dialog */}
>
);
};
export default CartDetails;