fendi-react-app/src/private/AddOrEditProductForm.jsx
2025-06-05 19:39:01 -06:00

137 lines
3.3 KiB
JavaScript

import React, { useState, useEffect } from 'react';
import { Box, Button, TextField, Grid, Avatar, Typography } from '@mui/material';
export default function AddOrEditProductForm({ onAdd, initialData, onCancel }) {
const [product, setProduct] = useState({
name: '',
price: '',
provider: '',
stock: '',
category: '',
representation: ''
});
useEffect(() => {
if (initialData) {
setProduct(initialData);
} else {
setProduct({
name: '',
price: '',
provider: '',
stock: '',
category: '',
representation: ''
});
}
}, [initialData]);
const handleChange = (e) => {
const { name, value } = e.target;
setProduct((prev) => ({
...prev,
[name]: name === 'price' || name === 'stock' ? Number(value) : value
}));
};
const handleImageChange = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onloadend = () => {
setProduct((prev) => ({ ...prev, representation: reader.result }));
};
reader.readAsDataURL(file);
};
const handleSubmit = () => {
if (onAdd) {
onAdd(product);
}
};
return (
<Box mt={2}>
<TextField
fullWidth
label="Name"
name="name"
value={product.name}
onChange={handleChange}
margin="normal"
/>
<TextField
fullWidth
label="Price"
name="price"
type="number"
value={product.price}
onChange={handleChange}
margin="normal"
/>
<Grid container spacing={2}>
<Grid item xs={6}>
<TextField
fullWidth
label="Provider"
name="provider"
value={product.provider}
onChange={handleChange}
margin="normal"
/>
</Grid>
<Grid item xs={6}>
<TextField
fullWidth
label="Stock"
name="stock"
type="number"
value={product.stock}
onChange={handleChange}
margin="normal"
/>
</Grid>
</Grid>
<TextField
fullWidth
label="Category"
name="category"
value={product.category}
onChange={handleChange}
margin="normal"
/>
<Grid item xs={12} textAlign="center">
{product.representation && (
<Box mb={1}>
<Typography variant="subtitle1" gutterBottom>Representation</Typography>
<Avatar
variant="rounded"
src={product.representation}
sx={{ width: 120, height: 120, mx: 'auto' }}
imgProps={{
style: {
objectFit: 'contain',
width: '100%',
height: '100%',
}
}}
/>
</Box>
)}
<Button variant="outlined" component="label">
Upload Image
<input type="file" hidden accept="image/*" onChange={handleImageChange} />
</Button>
</Grid>
<Box mt={2}>
{/* Fields... */}
<Box display="flex" justifyContent="flex-end" gap={1} mt={2}>
<Button onClick={onCancel}>Cancel</Button>
<Button variant="contained" onClick={handleSubmit}>Save</Button>
</Box>
</Box>
</Box>
);
}