import { useState, useEffect } from "react"; import { useLocation, Link } from "react-router-dom"; import { X, ChevronLeft, Plus, Trash2 } from "lucide-react"; const Selling = () => { const [products, setProducts] = useState([]); const [showForm, setShowForm] = useState(false); const storedUser = JSON.parse(sessionStorage.getItem("user")); const [categories, setCategories] = useState([]); const [categoryMapping, setCategoryMapping] = useState({}); const [selectedCategory, setSelectedCategory] = useState(""); const [originalProduct, setOriginalProduct] = useState(null); const [editingProduct, setEditingProduct] = useState({ name: "", price: "", description: "", categories: [], images: [], }); function reloadPage() { var doctTimestamp = new Date(performance.timing.domLoading).getTime(); var now = Date.now(); var tenSec = 10 * 1000; if (now > doctTimestamp + tenSec) { location.reload(); } } // Fetch categories from API useEffect(() => { const fetchCategories = async () => { try { const response = await fetch("http://localhost:3030/api/category"); if (!response.ok) throw new Error("Failed to fetch categories"); const responseJson = await response.json(); const data = responseJson.data; // Create an array of category names for the dropdown const categoryNames = []; const mapping = {}; // Process the data properly to avoid rendering objects Object.entries(data).forEach(([id, name]) => { // Make sure each category name is a string const categoryName = String(name); categoryNames.push(categoryName); mapping[categoryName] = parseInt(id); }); setCategories(categoryNames); setCategoryMapping(mapping); } catch (error) { console.error("Error fetching categories:", error); } }; fetchCategories(); }, []); // Simulate fetching products from API/database on component mount useEffect(() => { const fetchProducts = async () => { try { // Replace with your actual API endpoint const response = await fetch( "http://localhost:3030/api/product/myProduct", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userID: storedUser.ID, }), }, ); if (!response.ok) { throw new Error("Network response was not ok"); } const datajson = await response.json(); setProducts(datajson.data); } catch (error) { console.error("Error fetching products:", error); // You might want to set an error state here } }; fetchProducts(); }, []); // Add userId to dependency array if it might change const handleSaveProduct = async () => { if (!(editingProduct.categories || []).length) { alert("Please select at least one category"); return; } try { const imagePaths = []; if (editingProduct.images && editingProduct.images.length > 0) { editingProduct.images.forEach((file) => { const simulatedPath = `/public/uploads/${file.name}`; imagePaths.push(simulatedPath); }); } else if (originalProduct?.images?.length > 0) { imagePaths.push(...originalProduct.images); } const categoryName = (editingProduct.categories || [])[0]; const categoryID = categoryMapping[categoryName] || originalProduct?.category || 1; const payload = { name: editingProduct.name || originalProduct?.name || "", price: parseFloat(editingProduct.price) || parseFloat(originalProduct?.price) || 0, qty: 1, userID: storedUser.ID, description: editingProduct.description || originalProduct?.description || "", category: categoryID, images: imagePaths, }; console.log("Sending payload:", payload); const endpoint = editingProduct.ProductID ? `http://localhost:3030/api/product/update/${editingProduct.ProductID}` : "http://localhost:3030/api/product/addProduct"; const method = editingProduct.ProductID ? "PUT" : "POST"; const response = await fetch(endpoint, { method, headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }); if (!response.ok) { const errorData = await response.text(); throw new Error( `${ editingProduct.ProductID ? "Failed to update" : "Failed to add" } product: ${errorData}`, ); } const data = await response.json(); console.log("Product saved:", data); // Reset form and hide it setShowForm(false); setEditingProduct({ name: "", price: "", description: "", categories: [], images: [], }); setOriginalProduct(null); // reset original as well reloadPage(); } catch (error) { console.error("Error saving product:", error); alert(`Error saving product: ${error.message}`); } }; // Handle product deletion const handleDeleteProduct = async (productId) => { try { // Replace with your actual API endpoint const response = await fetch( "http://localhost:3030/api/product/delProduct", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userID: storedUser.ID, productID: productId, }), }, ); console.log("deleteproodidt"); reloadPage(); if (!response.ok) { throw new Error("Network response was not ok"); } } catch (error) { console.error("Error fetching products:", error); // You might want to set an error state here } }; // Handle editing a product const handleEditProduct = (product) => { // Convert category ID to category name if needed const categoryName = getCategoryNameById(product.CategoryID); setEditingProduct({ ...product, categories: categoryName ? [categoryName] : [], images: product.images || [], // Ensure images array exists }); setShowForm(true); }; // Helper function to get category name from ID const getCategoryNameById = (categoryId) => { if (!categoryId || !categoryMapping) return null; // Find the category name by ID for (const [name, id] of Object.entries(categoryMapping)) { if (id === categoryId) { return name; } } return null; }; // Handle adding a new product const handleAddProduct = () => { setEditingProduct({ name: "", price: "", description: "", categories: [], images: [], }); setShowForm(true); }; const addCategory = () => { if ( selectedCategory && !(editingProduct.categories || []).includes(selectedCategory) ) { setEditingProduct((prev) => ({ ...prev, categories: [...(prev.categories || []), selectedCategory], })); setSelectedCategory(""); } }; const removeCategory = (categoryToRemove) => { setEditingProduct((prev) => ({ ...prev, categories: (prev.categories || []).filter( (cat) => cat !== categoryToRemove, ), })); }; const markAsSold = async () => { // This would call an API to move the product to the transaction table try { // API call would go here console.log( "Moving product to transaction table:", editingProduct.ProductID, ); // Toggle the sold status in the UI setEditingProduct((prev) => ({ ...prev, isSold: !prev.isSold, })); // You would add your API call here to update the backend } catch (error) { console.error("Error marking product as sold:", error); } }; return (
Please select at least one category
)}{editingProduct.images.length}{" "} {editingProduct.images.length === 1 ? "image" : "images"}{" "} selected
Current image:
You don't have any listings yet
${product.Price}
{product.CategoryID && ({product.Description}