import { useState, useEffect } from "react"; import { Link, useParams, useNavigate } from "react-router-dom"; import { ArrowLeft, Plus, X, Save, Trash } from "lucide-react"; const ItemForm = () => { const { id } = useParams(); // If id exists, we are editing, otherwise creating const navigate = useNavigate(); const isEditing = !!id; const [formData, setFormData] = useState({ title: "", price: "", category: "", condition: "", shortDescription: "", description: "", images: [], status: "active", }); const [originalData, setOriginalData] = useState(null); const [errors, setErrors] = useState({}); const [imagePreviewUrls, setImagePreviewUrls] = useState([]); const [isLoading, setIsLoading] = useState(isEditing); const [isSubmitting, setIsSubmitting] = useState(false); const [showDeleteModal, setShowDeleteModal] = useState(false); // Categories with icons const categories = [ "Electronics", "Furniture", "Books", "Kitchen", "Collectibles", "Clothing", "Sports & Outdoors", "Tools", "Toys & Games", "Other", ]; // Condition options const conditions = ["New", "Like New", "Good", "Fair", "Poor"]; // Status options const statuses = ["active", "inactive", "sold", "pending"]; // Fetch item data if editing useEffect(() => { if (isEditing) { // This would be an API call in a real app // Simulating API call with timeout setTimeout(() => { // Sample data for item being edited const itemData = { id: parseInt(id), title: "Dell XPS 13 Laptop - 2023 Model", price: 850, category: "Electronics", condition: "Like New", shortDescription: "Dell XPS 13 laptop in excellent condition. Intel Core i7, 16GB RAM, 512GB SSD. Includes charger and original box.", description: "Selling my Dell XPS 13 laptop. Only 6 months old and in excellent condition. Intel Core i7 processor, 16GB RAM, 512GB SSD. Battery life is still excellent (around 10 hours of regular use). Comes with original charger and box. Selling because I'm upgrading to a MacBook for design work.\n\nSpecs:\n- Intel Core i7 11th Gen\n- 16GB RAM\n- 512GB NVMe SSD\n- 13.4\" FHD+ Display (1920x1200)\n- Windows 11 Pro\n- Backlit Keyboard\n- Thunderbolt 4 ports", images: ["/image1.avif", "/image2.avif", "/image3.avif"], status: "active", datePosted: "2023-03-02", }; setFormData(itemData); setOriginalData(itemData); setImagePreviewUrls(itemData.images); setIsLoading(false); }, 1000); } }, [id, isEditing]); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value, }); // Clear error when field is edited if (errors[name]) { setErrors({ ...errors, [name]: null, }); } }; const handleImageChange = (e) => { e.preventDefault(); const files = Array.from(e.target.files); if (formData.images.length + files.length > 5) { setErrors({ ...errors, images: "Maximum 5 images allowed", }); return; } // Create preview URLs for the images const newImagePreviewUrls = [...imagePreviewUrls]; const newImages = [...formData.images]; files.forEach((file) => { const reader = new FileReader(); reader.onloadend = () => { newImagePreviewUrls.push(reader.result); setImagePreviewUrls(newImagePreviewUrls); }; reader.readAsDataURL(file); newImages.push(file); }); setFormData({ ...formData, images: newImages, }); // Clear error if any if (errors.images) { setErrors({ ...errors, images: null, }); } }; const removeImage = (index) => { const newImages = [...formData.images]; const newImagePreviewUrls = [...imagePreviewUrls]; newImages.splice(index, 1); newImagePreviewUrls.splice(index, 1); setFormData({ ...formData, images: newImages, }); setImagePreviewUrls(newImagePreviewUrls); }; const validateForm = () => { const newErrors = {}; if (!formData.title.trim()) newErrors.title = "Title is required"; if (!formData.price) newErrors.price = "Price is required"; if (isNaN(formData.price) || formData.price <= 0) newErrors.price = "Price must be a positive number"; if (!formData.category) newErrors.category = "Category is required"; if (!formData.condition) newErrors.condition = "Condition is required"; if (!formData.shortDescription.trim()) newErrors.shortDescription = "Short description is required"; if (!formData.description.trim()) newErrors.description = "Description is required"; if (formData.images.length === 0) newErrors.images = "At least one image is required"; setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e) => { e.preventDefault(); if (!validateForm()) { // Scroll to the first error const firstErrorField = Object.keys(errors)[0]; document .getElementsByName(firstErrorField)[0] ?.scrollIntoView({ behavior: "smooth" }); return; } setIsSubmitting(true); // Simulate API call to post/update the item setTimeout(() => { console.log("Form submitted:", formData); setIsSubmitting(false); // Show success and redirect to listings alert(`Item successfully ${isEditing ? "updated" : "created"}!`); navigate("/selling"); }, 1500); }; const handleDelete = () => { setIsSubmitting(true); // Simulate API call to delete the item setTimeout(() => { console.log("Item deleted:", id); setIsSubmitting(false); setShowDeleteModal(false); // Show success and redirect to listings alert("Item successfully deleted!"); navigate("/selling"); }, 1500); }; // Show loading state if necessary if (isLoading) { return (
Back to listings
); } return (
{/* Breadcrumb & Back Link */}
Back to listings

{isEditing ? "Edit Item" : "Create New Listing"}

{isEditing && ( )}
{/* Title */}
{errors.title && (

{errors.title}

)}
{/* Price, Category, Status (side by side on larger screens) */}
{errors.price && (

{errors.price}

)}
{errors.category && (

{errors.category}

)}
{isEditing && (
)}
{/* Condition */}
{conditions.map((condition) => ( ))}
{errors.condition && (

{errors.condition}

)}
{/* Short Description */}

{formData.shortDescription.length}/150 characters

{errors.shortDescription && (

{errors.shortDescription}

)}
{/* Full Description */}

Use blank lines to separate paragraphs.

{errors.description && (

{errors.description}

)}
{/* Image Upload */}
{/* Image Preview Area */}
{imagePreviewUrls.map((url, index) => (
{`Preview
))} {/* Upload Button (only show if less than 5 images) */} {formData.images.length < 5 && ( )}
{errors.images && (

{errors.images}

)}
{/* Submit Button */}
{/* Delete Confirmation Modal */} {showDeleteModal && (

Delete Listing

Are you sure you want to delete {formData.title}? This action cannot be undone.

)}
); }; export default ItemForm;