import { PlusOutlined } from "@ant-design/icons"; import { Upload, message, Image } from "antd"; import axios from "axios"; import { getSession } from "next-auth/react"; import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { toast } from "react-toastify"; import { cleanImage } from "../../services/imageHandling"; const getBase64 = file => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); }); const ImageUploadPopUp = ({ isUpdate, setimagesArrayComponent, populatedImages, imagesArrayComponent }) => { // const { loadedUser } = useSelector(state => state.loadedUser); const [session, setSession] = useState(); const [previewOpen, setPreviewOpen] = useState(false); const [previewImage, setPreviewImage] = useState(""); const [fileList, setFileList] = useState([]); const [uploading, setUploading] = useState(false); console.log("populatedImages", populatedImages); const transformImageData = images => { return images.map((image, index) => ({ uid: index, name: `image-${index}.jpg`, // You can adjust the name based on your requirements status: "done", url: image.url, // Assuming image.url is the URL of the image id: image.id, deleteId: image.deleteId })); }; useEffect(() => { const fetchSession = async () => { setSession(await getSession()); }; fetchSession(); // dispatch(getLoggedInVendor()); }, []); useEffect(() => { // console.log("populatedImages.id", populatedImages.id); if (!populatedImages) { return; } const initialImages = transformImageData([{ url: cleanImage(populatedImages.image.data?.attributes), deleteId: populatedImages.image.data?.id, id: populatedImages.id }]); if (populatedImages) { setFileList(initialImages); } }, [populatedImages]); console.log("fileList", fileList); // let formData = new FormData(); let finalId; const handlePreview = async file => { if (!file.url && !file.preview) { file.preview = await getBase64(file.originFileObj); } setPreviewImage(file.url || file.preview); setPreviewOpen(true); }; const handleImageChange = async info => { console.log("info", info); const newFileList = [...info.fileList]; if (info.file.status === "uploading") { setUploading(true); setFileList(newFileList); return; } if (info.file.status === "done") { let formData = new FormData(); formData.append("files", info.file.originFileObj); try { const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/upload`, formData, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${session.jwt}` } }); if (response.status === 200) { const newFileId = response.data[0].id; // Update the file list with the new file ID const updatedFileList = newFileList.map(file => { if (file.uid === info.file.uid) { return { ...file, id: newFileId, url: response.data[0].url // You can add any other response data you need here }; } return file; }); setFileList(updatedFileList); setimagesArrayComponent(newFileId); message.success(`${info.file.name} uploaded successfully.`); } } catch (error) { message.error(`${info.file.name} upload failed.`); } finally { setUploading(false); } } else if (info.file.status === "removed") { // Handle file removal if needed const updatedFileList = newFileList.filter(file => file.uid !== info.file.uid); setFileList(updatedFileList); } }; const handleCustomRequest = ({ file, onSuccess, onError }) => { setTimeout(() => { onSuccess({ id: finalId }, file); }, 2000); }; const handleRemove = async file => { console.log("handle remove", file); let imageId; if (file.deleteId) { imageId = file.deleteId; } else { imageId = file.id; } if (!imageId) { console.log("delete here"); message.error(`Failed to remove ${file.name}. Image ID not found.`); return; } setFileList([]); try { const res = await axios.delete(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/upload/files/${imageId}`, { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${session.jwt}` } }); // Replace with your Strapi delete endpoint console.log("delete res", res); message.success(`${file.name} file removed successfully.`); setimagesArrayComponent(null); setFileList(prevFileList => prevFileList.filter(item => item.uid !== file.uid)); } catch (error) { message.error(`Failed to remove ${file.name}`); } }; return ( <div> <Upload // customRequest={handleCustomRequest} // enterButton={true} // showUploadList={{ showRemoveIcon: false }} listType="picture-card" fileList={fileList} // multiple={false} onChange={handleImageChange} onRemove={handleRemove} onPreview={handlePreview} > {fileList?.length >= 1 ? null : ( <div> <PlusOutlined /> <div style={{ marginTop: 8 }}>Upload</div> </div> )} </Upload> {previewImage && ( <Image wrapperStyle={{ display: "none" // zIndex: 23 }} preview={{ visible: previewOpen, onVisibleChange: visible => setPreviewOpen(visible), afterOpenChange: visible => !visible && setPreviewImage("") }} src={previewImage} /> )} {/* <button type="button" onClick={handleUpload} disabled={fileList ? fileList.length === 0 : true} loading={uploading} style={{ marginTop: 16 }}> {uploading ? "Uploading" : "Start Upload"} </button> */} </div> ); }; export default ImageUploadPopUp;