import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import './Checkout.css'
function Checkout({ user }) {
const location = useLocation()
const navigate = useNavigate()
const basket = location.state?.basket || []
const [success, setSuccess] = useState(false)
const [error, setError] = useState('')
const total = basket.reduce((sum, item) => {
return sum + item.product_price * item.quantity
}, 0)
const placeOrder = async () => {
if (!user) { navigate('/login'); return }
const res = await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
customerID: user.customerID,
items: basket.map(item => ({
productID: item.productID,
quantity: item.quantity
}))
})
})
const data = await res.json()
if (!res.ok) { setError(data.error); return }
setSuccess(true)
}
if (success) {
return (
<div className="page">
<h1>Order Placed!</h1>
<p>Thank you for your order.</p>
<button className="order-btn" onClick={() => navigate('/orders')}>
View My Orders
</button>
</div>
)
}
return (
<div className="page">
<h1>Checkout</h1>
{basket.length === 0 ? <p>Your basket is empty.</p> : (
<>
{basket.map((item, index) => (
<div key={index} className="checkout-item">
<p className="item-name">{item.product_name}</p>
<p>Quantity: {item.quantity}</p>
<p>£{(item.product_price * item.quantity).toFixed(2)}</p>
</div>
))}
<div className="checkout-total">
<h2>Total: £{total.toFixed(2)}</h2>
</div>
{error && <p className="error">{error}</p>}
<button className="order-btn" onClick={placeOrder}>Place Order</button>
</>
)}
</div>
)
}
export default Checkout
.page { padding: 30px; }
.page h1 { margin-bottom: 20px; }
.checkout-item {
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
margin-bottom: 10px;
max-width: 500px;
}
.item-name { font-weight: 700; margin-bottom: 5px; color: #144A5C; }
.checkout-total { margin: 20px 0; }
.checkout-total h2 { color: #A2C24A; }
.error {
color: white;
background: red;
padding: 10px;
border-radius: 6px;
margin-bottom: 10px;
}
.order-btn {
background: #A2C24A;
color: white;
border: none;
padding: 12px 30px;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
font-family: 'Gluten', cursive;
}
Top comments (0)