import React, { useState } from 'react'; import { Box, Button, FormControl, FormLabel, Grid, GridItem, Heading, InputGroup, InputLeftAddon, Text, Textarea, useColorModeValue, } from '@chakra-ui/react'; import CurrencyInput from 'react-currency-input-field'; import { AiOutlineFileText, AiOutlineNumber } from 'react-icons/ai'; import { BsCurrencyDollar, BsMarkdown } from 'react-icons/bs'; import InlineLabelInput from '../../../../global/components/FormControl/InlineLabelInput'; import IconTextDuo from '../../../../global/components/IconTextDuo'; import { Manage as i18n } from '../../../../global/i18n'; import store from '../../../../redux/store'; import FileUpload from '../FileUpload'; import DeletableImage from '../DeletableImage'; import { uploadImage } from '../../../../global/api'; const InputGroupStyle = { marginTop: '1rem', marginBottom: '1rem', }; export default ({ product }) => { const [loading, setLoading] = useState(false); const [state, setState] = useState({ name: product.name, description: product.description, quantity: product.quantity, price: product.price, images: product.images, newImages: [], }); const save = async () => { setLoading(true); if (!state.name.length || !state.quantity || !state.price || !state.description) { store.dispatch({ type: 'SET_ALERT', data: { header: 'Missing Info', content: 'Not all required fields have been filled. Please provide this info to proceed.' } }); setLoading(false); return; } try { // Step 1: Upload image files // Join the old image files with the new ones as well const imageUrls = (await Promise.all(state.newImages.map(uploadImage))).concat(state.images); // Step 2: Upload the rest // eslint-disable-next-line no-underscore-dangle const resp = await fetch(`/api/v1/products/${product._id}`, { method: 'PATCH', headers: { authorization: `Bearer ${window.localStorage.getItem('auth-token')}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ ...state, images: imageUrls.length, }), }); const data = await resp.json(); if (resp.ok) { store.dispatch({ type: 'SET_ALERT', data: { header: 'Item Updated Successfully!', content: 'Your Changes have Been Saved and Will Be Reflected on the Management Page' } }); } else { store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Add Item', content: JSON.stringify(data) } }); } } catch (ex) { store.dispatch({ type: 'SET_ALERT', data: { header: 'Failed to Edit Item in Catch Block', content: ex } }); } setLoading(false); }; return (