Certainly! Below is a comprehensive solution addressing your requirements. This includes converting your current TypeScript components to JavaScript, enhancing the UI/UX with Tailwind CSS, ensuring responsiveness, fixing the issue with sizes nested inside colors in the EditProduct component, improving font usage, and optimizing performance.
1. Overview of Changes
a. TypeScript to JavaScript
All TypeScript-specific syntax, including type annotations and interfaces, have been removed. The components are now written in pure JavaScript (.jsx).
b. UI/UX Enhancements
- Tailwind CSS Improvements: Utilized more Tailwind CSS utilities to enhance the visual aesthetics and responsiveness of the components.
- Consistent Layouts: Ensured that both
AddProduct and EditProduct dialogs have a consistent layout, especially nesting sizes within colors when applicable.
- Improved Forms: Enhanced form elements with better spacing, borders, and hover effects for improved interactivity.
- Responsive Design: Ensured that the components are fully responsive across various device sizes.
c. Font Improvement
- Global Font: Applied the 'Inter' font globally to ensure a modern and clean look across all components.
d. Fixing Sizes Inside Colors Issue
- EditProduct Component: Modified the structure to nest sizes within their respective color sections, aligning it with the
AddProduct component's behavior.
e. Performance Optimizations
- React
memo: Used React.memo to prevent unnecessary re-renders of components.
- Debouncing Search Input: Retained the debounce functionality to optimize search performance.
2. Updated Components
a. pages/products.jsx
// pages/products.jsx
"use client";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import Head from "next/head";
import Image from "next/image";
import {
Search,
Grid,
List,
Plus,
Edit,
Trash2,
ChevronLeft,
ChevronRight,
} from "lucide-react";
import AddProductDialog from "@/components/AddProductDialog";
import EditProduct from "@/components/EditProduct";
import LoadingSpinner from "@/components/LoadingSpinner";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import debounce from "lodash/debounce";
import { getToken } from "@/app/auth";
const formatDate = (dateString) => {
const date = new Date(dateString);
return date.toLocaleDateString(); // 'MM/DD/YYYY' format
};
const PRODUCTS_PER_PAGE = 15;
const ProductsPage = () => {
// State Variables
const [products, setProducts] = useState([]);
const [brands, setBrands] = useState([]);
const [brandMap, setBrandMap] = useState({});
const [currentPage, setCurrentPage] = useState(1);
const [searchTerm, setSearchTerm] = useState("");
const [viewMode, setViewMode] = useState("grid");
const [sortBy, setSortBy] = useState("created_at");
const [sortOrder, setSortOrder] = useState("desc");
const [isAddProductDialogOpen, setIsAddProductDialogOpen] = useState(false);
const [isEditProductDialogOpen, setIsEditProductDialogOpen] = useState(false);
const [productToEdit, setProductToEdit] = useState(null);
const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
const [productToDelete, setProductToDelete] = useState(null);
const [isDeleting, setIsDeleting] = useState(false);
const [totalPages, setTotalPages] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [searchInput, setSearchInput] = useState("");
// Debounce the search input to prevent excessive API calls
const debouncedSearch = useMemo(
() =>
debounce((term) => {
setSearchTerm(term);
setCurrentPage(1);
}, 300),
[]
);
useEffect(() => {
debouncedSearch(searchInput);
return () => {
debouncedSearch.cancel();
};
}, [searchInput, debouncedSearch]);
const handleSearchChange = (e) => {
setSearchInput(e.target.value);
};
// Fetch Brand Details
const fetchBrands = useCallback(async () => {
const token = getToken(); // Retrieve the token from localStorage
if (!token) {
toast.error("You must be logged in.");
return;
}
try {
const response = await fetch(`http://localhost:4000/subcategories/brands`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error("Failed to fetch brands");
}
const data = await response.json();
setBrands(data);
// Create a mapping from brand_id to brand_name for easy lookup
const map = {};
data.forEach((brand) => {
map[brand.id] = brand.name;
});
setBrandMap(map);
} catch (error) {
console.error("Error fetching brands:", error);
toast.error("Failed to fetch brands. Please try again.");
}
}, []);
// Fetch Products
const fetchProducts = useCallback(async () => {
setIsLoading(true);
const token = getToken(); // Retrieve the token from localStorage
if (!token) {
toast.error("You must be logged in.");
setIsLoading(false);
return;
}
try {
const response = await fetch(
`http://localhost:4000/products?page=${currentPage}&limit=${PRODUCTS_PER_PAGE}&search=${encodeURIComponent(
searchTerm
)}&sortBy=${sortBy}&sortOrder=${sortOrder}`,
{
cache: "no-cache",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data = await response.json();
setProducts(data.products);
setTotalPages(data.totalPages);
} catch (error) {
console.error("Error fetching products:", error);
toast.error("Failed to fetch products. Please try again.");
} finally {
setIsLoading(false);
}
}, [currentPage, searchTerm, sortBy, sortOrder]);
useEffect(() => {
fetchBrands();
}, [fetchBrands]);
useEffect(() => {
fetchProducts();
}, [fetchProducts]);
const filteredProducts = useMemo(() => {
return products
.filter((product) =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
)
.sort((a, b) => {
if (a[sortBy] === null) return 1;
if (b[sortBy] === null) return -1;
if (sortOrder === "asc") {
return a[sortBy].toString().localeCompare(b[sortBy].toString());
} else {
return b[sortBy].toString().localeCompare(a[sortBy].toString());
}
});
}, [products, searchTerm, sortBy, sortOrder]);
const handleEditClick = useCallback((product) => {
setProductToEdit(product);
setIsEditProductDialogOpen(true);
}, []);
const handleDeleteClick = useCallback((product) => {
setProductToDelete(product);
setIsDeleteConfirmOpen(true);
}, []);
const handleDeleteConfirm = useCallback(async () => {
if (productToDelete) {
setIsDeleting(true);
const token = getToken(); // the token from localStorage
if (!token) {
toast.error("You must be logged in.");
setIsDeleting(false);
return;
}
try {
const response = await fetch(
`http://localhost:4000/products/${productToDelete.id}`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
if (!response.ok) {
throw new Error("Failed to delete product");
}
setProducts((prevProducts) =>
prevProducts.filter((p) => p.id !== productToDelete.id)
);
setIsDeleteConfirmOpen(false);
toast.success("Product deleted successfully");
} catch (error) {
console.error("Error deleting product:", error);
toast.error("Failed to delete product. Please try again.");
} finally {
setIsDeleting(false);
}
}
}, [productToDelete]);
// Helper function to get the first color's first size information
const getFirstColorSizeInfo = useCallback((product) => {
if (product.has_color && product.has_size) {
const firstColor = product.colors[0];
if (firstColor) {
const sizesForColor = product.sizes.filter(
(size) => size.color_id === firstColor.id
);
const firstSize = sizesForColor[0];
if (firstSize) {
return {
colorName: firstColor.name,
sizeName: firstSize.name,
price: firstSize.price,
qty: firstSize.qty,
sold: Math.abs(firstSize.sold), // Ensuring 'sold' is absolute
};
}
}
}
return null;
}, []);
// Updated helper functions to accommodate the new logic
const getProductPrice = useCallback(
(product) => {
const colorSizeInfo = getFirstColorSizeInfo(product);
if (colorSizeInfo) {
return `$${colorSizeInfo.price.toLocaleString()}`;
}
if (!product.has_color && !product.has_size)
return `$${product.price.toLocaleString()}`;
if (product.colors.length > 0 && product.colors[0].price !== null)
return `$${product.colors[0].price.toLocaleString()}`;
if (product.sizes.length > 0)
return `$${product.sizes[0].price.toLocaleString()}`;
return "N/A";
},
[getFirstColorSizeInfo]
);
const getProductQuantity = useCallback(
(product) => {
const colorSizeInfo = getFirstColorSizeInfo(product);
if (colorSizeInfo) {
return colorSizeInfo.qty;
}
if (product.qty !== null && product.qty !== 0) return product.qty;
if (product.colors.length > 0 && product.colors[0].qty !== null)
return product.colors[0].qty;
if (product.sizes.length > 0) return product.sizes[0].qty;
return "N/A";
},
[getFirstColorSizeInfo]
);
const getProductSold = useCallback((product) => {
let total = 0;
if (product.colors) {
product.colors.forEach((color) => {
if (color.sizes.length > 0) {
color.sizes.forEach((size) => (total += size.sold));
} else {
total += color.sold;
}
});
}
if (product.sizes) {
product.sizes.forEach((size) => {
total += size.sold;
});
}
total += product.sold;
return Math.abs(total);
}, []);
// Pagination Handler
const handlePageChange = useCallback((newPage) => {
setCurrentPage(newPage);
window.scrollTo({ top: 0, behavior: "smooth" });
}, []);
return (
<div className="font-inter min-h-screen bg-gray-100">
<Head>
<title>Products - Naay Store</title>
<link rel="icon" href="/favicon.ico" />
{/* Link to Inter font from Google Fonts */}
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap"
rel="stylesheet"
/>
</Head>
<main className="container mx-auto px-4 py-8">
{/* Header Section */}
<div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0">
<h1 className="text-3xl font-bold text-gray-900">All Products</h1>
<button
className="flex items-center rounded-md bg-green-500 px-4 py-2 text-white transition duration-300 hover:bg-green-600"
onClick={() => setIsAddProductDialogOpen(true)}
>
<Plus className="mr-2" size={20} />
Add Product
</button>
</div>
{/* Search and Filters */}
<div className="mb-8 flex flex-col items-center justify-between space-y-4 md:flex-row md:space-y-0">
{/* Search */}
<div className="relative w-full max-w-md">
<input
type="text"
placeholder="Search products..."
className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={searchInput}
onChange={handleSearchChange}
/>
<Search className="absolute left-3 top-2.5 h-5 w-5 text-gray-400" />
</div>
{/* Sort & Sort Order & View Modes */}
<div className="flex items-center space-x-4">
<select
className="rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
>
<option value="name">Sort by Name</option>
<option value="price">Sort by Price</option>
<option value="created_at">Sort by Created Date</option>
</select>
<select
className="rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
value={sortOrder}
onChange={(e) => setSortOrder(e.target.value)}
>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
<button
className={`rounded-md p-2 ${
viewMode === "grid" ? "bg-blue-500 text-white" : "bg-gray-200"
}`}
onClick={() => setViewMode("grid")}
aria-label="Grid View"
>
<Grid className="h-5 w-5" />
</button>
<button
className={`rounded-md p-2 ${
viewMode === "list" ? "bg-blue-500 text-white" : "bg-gray-200"
}`}
onClick={() => setViewMode("list")}
aria-label="List View"
>
<List className="h-5 w-5" />
</button>
</div>
</div>
{/* Product List */}
{isLoading ? (
<div className="flex justify-center">
<LoadingSpinner />
</div>
) : (
<div
className={`grid gap-6 ${
viewMode === "grid"
? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
: "grid-cols-1"
}`}
>
{filteredProducts.map((product) => {
const colorSizeInfo = getFirstColorSizeInfo(product);
return (
<div
key={product.id}
className={`overflow-hidden rounded-lg bg-white shadow-md ${
viewMode === "list" ? "flex" : ""
} transition-transform hover:scale-105`}
>
{/* Product Image */}
<div
className={`${
viewMode === "list" ? "w-1/3" : "w-full"
} relative pb-[100%]`}
>
{product.images.length > 0 ? (
<Image
src={`https://storage.naayiq.com/resources/${product.images[0].url}`}
alt={product.name}
fill={true}
className="object-cover"
priority={false}
loading="lazy"
/>
) : (
<div className="flex items-center justify-center bg-gray-200">
<span className="text-gray-500">No Image</span>
</div>
)}
</div>
{/* Product Details */}
<div className={`p-4 ${viewMode === "list" ? "w-2/3" : ""}`}>
<h2 className="mb-2 text-xl font-semibold text-gray-800">
{product.name}
</h2>
<p
className="mb-4 text-sm text-gray-700"
style={{ direction: "rtl" }}
dangerouslySetInnerHTML={{
__html: product.description.replace(/\n/g, "<br />"),
}}
/>
<div className="mb-4 space-y-1">
{/* Display Price */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Price:</span>{" "}
{getProductPrice(product)}
</p>
{/* Display Quantity */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Quantity:</span>{" "}
{getProductQuantity(product)}
</p>
{/* Display Sold */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Sold:</span>{" "}
{getProductSold(product)}
</p>
{/* Display Created At */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Created at:</span>{" "}
{formatDate(product.created_at)}
</p>
{/* Display Has Color */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Has Color:</span>{" "}
{product.has_color ? "Yes" : "No"}
</p>
{/* Display Has Size */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Has Size:</span>{" "}
{product.has_size ? "Yes" : "No"}
</p>
{/* Display Brand */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Brand:</span>{" "}
{brandMap[product.brand_id] || `ID: ${product.brand_id}`}
</p>
{/* Display Categories */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Category:</span>{" "}
{product.categories
.map((category) => category.name)
.join(", ")}
</p>
{/* Display First Color's First Size Information */}
{colorSizeInfo && (
<div className="mt-2">
<p className="text-sm text-gray-600">
<span className="font-semibold">Color:</span>{" "}
{colorSizeInfo.colorName}
</p>
<p className="text-sm text-gray-600">
<span className="font-semibold">Size:</span>{" "}
{colorSizeInfo.sizeName}
</p>
<p className="text-sm text-gray-600">
<span className="font-semibold">Price:</span> $
{colorSizeInfo.price.toLocaleString()}
</p>
<p className="text-sm text-gray-600">
<span className="font-semibold">Quantity:</span>{" "}
{colorSizeInfo.qty}
</p>
<p className="text-sm text-gray-600">
<span className="font-semibold">Sold:</span>{" "}
{colorSizeInfo.sold}
</p>
</div>
)}
</div>
{/* Action Buttons */}
<div className="flex space-x-2">
<button
className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white transition duration-300 hover:bg-blue-600"
onClick={() => handleEditClick(product)}
>
<Edit className="mr-1 inline-block" size={16} />
Edit
</button>
<button
className="flex items-center rounded-md bg-red-500 px-4 py-2 text-white transition duration-300 hover:bg-red-600"
onClick={() => handleDeleteClick(product)}
>
<Trash2 className="mr-1 inline-block" size={16} />
Delete
</button>
</div>
</div>
</div>
);
})}
</div>
)}
{/* Pagination Controls */}
{!isLoading && totalPages > 1 && (
<div className="mt-8 flex items-center justify-center space-x-2">
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => handlePageChange(Math.max(currentPage - 1, 1))}
disabled={currentPage === 1}
>
Previous
</button>
{/* Condensed Pagination with Ellipsis */}
{Array.from({ length: totalPages }, (_, i) => i + 1)
.filter(
(number) =>
number === 1 ||
number === totalPages ||
(number >= currentPage - 1 && number <= currentPage + 1)
)
.map((number, index, array) => {
if (index > 0 && number - array[index - 1] > 1) {
return (
<span key={`ellipsis-${number}`} className="text-gray-500">
...
</span>
);
}
return (
<button
key={number}
className={`rounded-md px-3 py-1 text-sm ${
currentPage === number
? "bg-blue-500 text-white"
: "bg-gray-200 text-gray-700"
}`}
onClick={() => handlePageChange(number)}
>
{number}
</button>
);
})}
<button
className="rounded-md bg-gray-200 px-3 py-1 text-sm text-gray-700 disabled:cursor-not-allowed disabled:opacity-50"
onClick={() =>
handlePageChange(Math.min(currentPage + 1, totalPages))
}
disabled={currentPage === totalPages}
>
Next
</button>
</div>
)}
</main>
{/* Add Product Dialog */}
{isAddProductDialogOpen && (
<AddProductDialog
isOpen={isAddProductDialogOpen}
onClose={() => setIsAddProductDialogOpen(false)}
onProductAdded={(newProduct) => {
setProducts((prevProducts) => [newProduct, ...prevProducts]);
toast.success("Product added successfully!");
}}
/>
)}
{/* Edit Product Dialog */}
{isEditProductDialogOpen && productToEdit && (
<EditProduct
isOpen={isEditProductDialogOpen}
onClose={() => {
setIsEditProductDialogOpen(false);
setProductToEdit(null);
fetchProducts(); // Refresh the product list after editing
}}
product={productToEdit}
onProductUpdated={(updatedProduct) => {
setProducts((prevProducts) =>
prevProducts.map((prod) =>
prod.id === updatedProduct.id ? updatedProduct : prod
)
);
toast.success("Product updated successfully!");
}}
/>
)}
{/* Delete Confirmation Modal */}
{isDeleteConfirmOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
<div className="w-11/12 max-w-md rounded-lg bg-white p-8">
<h2 className="mb-4 text-xl font-semibold text-gray-800">
Confirm Delete
</h2>
<p className="mb-8 text-gray-600">
Are you sure you want to delete{" "}
<span className="font-semibold">
{productToDelete?.name ?? "this product"}
</span>
?
</p>
<div className="flex justify-end space-x-4">
<button
className="flex items-center rounded-md bg-red-500 px-4 py-2 text-white transition duration-300 hover:bg-red-600"
onClick={handleDeleteConfirm}
disabled={isDeleting}
>
<Trash2 className="mr-1 inline-block" size={16} />
{isDeleting ? "Deleting..." : "Yes, Delete"}
</button>
<button
className="rounded-md bg-gray-300 px-4 py-2 text-gray-700 transition duration-300 hover:bg-gray-400"
onClick={() => setIsDeleteConfirmOpen(false)}
disabled={isDeleting}
>
Cancel
</button>
</div>
</div>
</div>
)}
{/* Toast Notifications */}
<ToastContainer />
</div>
);
};
export default React.memo(ProductsPage);
b. components/EditProduct.jsx
// components/EditProduct.jsx
"use client";
import { useState, useEffect } from "react";
import { X, Plus, Trash2 } from "lucide-react";
import MultipartFileUploader from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import { getToken } from "@/app/auth";
const EditProduct = ({ isOpen, onClose, product, onProductUpdated }) => {
const [editedProduct, setEditedProduct] = useState({
...product,
sizes: product.sizes || [],
colors: product.colors.map((color) => ({
...color,
sizes: color.sizes || [],
})),
images: [],
});
const [categories, setCategories] = useState([]);
const [brands, setBrands] = useState([]);
useEffect(() => {
fetchCategories();
fetchBrands();
}, []);
const fetchCategories = async () => {
try {
const response = await fetch(
"http://localhost:4000/subcategories/non-brands"
);
const data = await response.json();
setCategories(data);
} catch (error) {
console.error("Error fetching categories:", error);
}
};
const fetchBrands = async () => {
try {
const response = await fetch("http://localhost:4000/subcategories/brands");
const data = await response.json();
setBrands(data);
} catch (error) {
console.error("Error fetching brands:", error);
}
};
const handleDeleteColor = (colorIndex) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors.splice(colorIndex, 1);
return { ...prevProduct, colors: newColors };
});
};
const handleDeleteSize = (colorIndex, sizeIndex) => {
setEditedProduct((prevProduct) => {
if (colorIndex === -1) {
const newSizes = [...prevProduct.sizes];
newSizes.splice(sizeIndex, 1);
return { ...prevProduct, sizes: newSizes };
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes.splice(sizeIndex, 1);
return { ...prevProduct, colors: newColors };
}
});
};
const handleInheritImagesChange = (variantType, colorIndex, sizeIndex) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (variantType === "color") {
updatedProduct.colors[colorIndex].inheritImages =
!updatedProduct.colors[colorIndex].inheritImages;
if (
updatedProduct.colors[colorIndex].inheritImages &&
colorIndex > 0
) {
const prevColor = updatedProduct.colors[colorIndex - 1];
updatedProduct.colors[colorIndex].images = [...prevColor.images];
}
} else if (variantType === "size") {
if (colorIndex === -1) {
updatedProduct.sizes[sizeIndex].inheritImages =
!updatedProduct.sizes[sizeIndex].inheritImages;
if (
updatedProduct.sizes[sizeIndex].inheritImages &&
sizeIndex > 0
) {
const prevSize = updatedProduct.sizes[sizeIndex - 1];
updatedProduct.sizes[sizeIndex].images = [...prevSize.images];
}
} else {
updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages =
!updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages;
if (
updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages &&
sizeIndex > 0
) {
const prevSize = updatedProduct.colors[colorIndex].sizes[sizeIndex - 1];
updatedProduct.colors[colorIndex].sizes[sizeIndex].images = [
...prevSize.images,
];
}
}
}
return updatedProduct;
});
};
const handleCategoryToggle = (categoryId) => {
setEditedProduct((prevProduct) => {
const updatedCategories = prevProduct.categories.some(
(cat) => cat.id === categoryId
)
? prevProduct.categories.filter((cat) => cat.id !== categoryId)
: [
...prevProduct.categories,
{
id: categoryId,
name: categories.find((cat) => cat.id === categoryId)?.name || "",
},
];
return { ...prevProduct, categories: updatedCategories };
});
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setEditedProduct((prevProduct) => ({
...prevProduct,
[name]: value,
}));
};
const handleBrandChange = (e) => {
setEditedProduct((prevProduct) => ({
...prevProduct,
brand_id: parseInt(e.target.value),
}));
};
const handleAddColor = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
colors: [
...prevProduct.colors,
{ name: "", price: null, qty: null, sizes: [], images: [] },
],
}));
};
const handleAddSize = (colorIndex) => {
setEditedProduct((prevProduct) => {
if (colorIndex === -1) {
return {
...prevProduct,
sizes: [
...prevProduct.sizes,
{ name: "", price: "", qty: "", images: [] },
],
};
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes.push({
name: "",
price: "",
qty: "",
images: [],
});
return {
...prevProduct,
colors: newColors,
};
}
});
};
const handleColorChange = (index, field, value) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors[index] = {
...newColors[index],
[field]: value,
};
return { ...prevProduct, colors: newColors };
});
};
const handleSizeChange = (colorIndex, sizeIndex, field, value) => {
setEditedProduct((prevProduct) => {
if (colorIndex === -1) {
const newSizes = [...prevProduct.sizes];
newSizes[sizeIndex] = {
...newSizes[sizeIndex],
[field]: value,
images: newSizes[sizeIndex].images || [],
};
return { ...prevProduct, sizes: newSizes };
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes[sizeIndex] = {
...newColors[colorIndex].sizes[sizeIndex],
[field]: value,
images: newColors[colorIndex].sizes[sizeIndex].images || [],
};
return { ...prevProduct, colors: newColors };
}
});
};
const handleImageUpload = (fileIds, variantType, colorIndex, sizeIndex) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (variantType === "color") {
updatedProduct.colors[colorIndex].images = fileIds;
} else if (variantType === "size") {
if (colorIndex === -1) {
updatedProduct.sizes[sizeIndex].images = fileIds;
} else {
updatedProduct.colors[colorIndex].sizes[sizeIndex].images = fileIds;
}
} else {
updatedProduct.images = fileIds;
}
return updatedProduct;
});
};
const handleSubmit = async (e) => {
e.preventDefault();
const productType =
editedProduct.has_color && editedProduct.has_size
? "color_size"
: editedProduct.has_color
? "color"
: editedProduct.has_size
? "size"
: "simple";
const productData = {
...editedProduct,
product_type: productType,
category_ids: editedProduct.categories.map((cat) => cat.id),
hasColor: editedProduct.has_color,
hasSize: editedProduct.has_size,
colors: editedProduct.has_color
? editedProduct.colors.map((color) => ({
id: color.id,
name: color.name,
price: color.price ? parseFloat(color.price) : null,
qty: color.qty ? parseInt(color.qty) : null,
hasSize: editedProduct.has_size,
sizes: editedProduct.has_size
? color.sizes.map((size) => ({
id: size.id,
name: size.name,
price: parseFloat(size.price),
qty: parseInt(size.qty),
images: size.images,
}))
: [],
images: color.images,
}))
: [],
sizes:
editedProduct.has_size && !editedProduct.has_color
? editedProduct.sizes.map((size) => ({
id: size.id,
name: size.name,
price: parseFloat(size.price),
qty: parseInt(size.qty),
images: size.images,
}))
: [],
price: editedProduct.price ? parseFloat(editedProduct.price) : null,
qty: editedProduct.qty ? parseInt(editedProduct.qty) : null,
images: editedProduct.images,
};
const token = getToken();
if (!token) {
toast.error("You must be logged in to edit the product.");
return;
}
try {
const response = await fetch(
`http://localhost:4000/products/${editedProduct.id}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(productData),
}
);
if (!response.ok) {
throw new Error("Failed to update product");
}
const updatedProduct = await response.json();
toast.success("Product updated successfully!");
onProductUpdated(updatedProduct);
onClose();
} catch (error) {
console.error("Error updating product:", error);
toast.error("Failed to update product. Please try again.");
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto">
<div className="relative w-full max-w-3xl bg-white rounded-lg p-8 shadow-lg">
{/* Close Button */}
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
>
<X size={24} />
</button>
<h2 className="mb-6 text-2xl font-bold">Edit Product</h2>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Product Name */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="name">
Product Name
</label>
<input
type="text"
id="name"
name="name"
value={editedProduct.name}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
{/* Description */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="description">
Description
</label>
<textarea
id="description"
name="description"
value={editedProduct.description}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
rows={4}
style={{ direction: "rtl" }}
required
></textarea>
</div>
{/* Categories */}
<div>
<label className="block text-sm font-semibold text-gray-700">Categories</label>
<div className="mt-2 flex flex-wrap gap-2">
{categories.map((category) => (
<button
key={category.id}
type="button"
onClick={() => handleCategoryToggle(category.id)}
className={`rounded-full px-4 py-2 text-sm ${
editedProduct.categories.some((cat) => cat.id === category.id)
? "bg-blue-500 text-white"
: "bg-gray-200 text-gray-700"
}`}
>
{category.name}
</button>
))}
</div>
</div>
{/* Brand */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="brand">
Brand
</label>
<select
id="brand"
name="brand"
value={editedProduct.brand_id}
onChange={handleBrandChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
>
<option value="">Select a brand</option>
{brands.map((brand) => (
<option key={brand.id} value={brand.id}>
{brand.name}
</option>
))}
</select>
</div>
{/* Has Color */}
<div className="flex items-center">
<input
type="checkbox"
id="has_color"
checked={editedProduct.has_color}
onChange={() =>
setEditedProduct((prev) => ({
...prev,
has_color: !prev.has_color,
colors: prev.has_color ? [] : prev.colors,
}))
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_color" className="ml-2 text-sm font-medium text-gray-700">
Has Color?
</label>
</div>
{/* Colors */}
{editedProduct.has_color && (
<div className="mt-4">
<label className="block text-sm font-semibold text-gray-700">Colors</label>
<div className="mt-2 space-y-4">
{editedProduct.colors.map((color, colorIndex) => (
<div key={colorIndex} className="rounded-md border p-4">
{/* Color Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Color Name
</label>
<input
type="text"
value={color.name}
onChange={(e) =>
handleColorChange(colorIndex, "name", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteColor(colorIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Color"
>
<Trash2 size={16} />
</button>
</div>
{/* Color Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={color.price || ""}
onChange={(e) =>
handleColorChange(colorIndex, "price", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={color.qty || ""}
onChange={(e) =>
handleColorChange(colorIndex, "qty", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{colorIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={color.inheritImages || false}
onChange={() =>
handleInheritImagesChange("color", colorIndex, null)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous color
</label>
</div>
)}
{/* Image Uploader */}
{!color.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "color", colorIndex, null)
}
existingImages={color.images}
/>
</div>
)}
{/* Has Size */}
{editedProduct.has_size && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
id={`has_size_${colorIndex}`}
checked={color.hasSize || false}
onChange={() => {
setEditedProduct((prev) => {
const newColors = [...prev.colors];
newColors[colorIndex].hasSize = !newColors[colorIndex].hasSize;
newColors[colorIndex].sizes = newColors[colorIndex].hasSize
? newColors[colorIndex].sizes
: [];
return { ...prev, colors: newColors };
});
}}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label
htmlFor={`has_size_${colorIndex}`}
className="ml-2 text-sm font-medium text-gray-700"
>
Has Size?
</label>
</div>
)}
{/* Sizes */}
{editedProduct.has_size && color.hasSize && (
<div className="mt-4 space-y-4">
{color.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="rounded-md border p-4">
{/* Size Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Size Name
</label>
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"name",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteSize(colorIndex, sizeIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Size"
>
<Trash2 size={16} />
</button>
</div>
{/* Size Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={size.price || ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"price",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={size.qty || ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"qty",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{sizeIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={size.inheritImages || false}
onChange={() =>
handleInheritImagesChange(
"size",
colorIndex,
sizeIndex
)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous size
</label>
</div>
)}
{/* Image Uploader */}
{!size.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(
fileIds,
"size",
colorIndex,
sizeIndex
)
}
existingImages={size.images}
/>
</div>
)}
</div>
))}
{/* Add Size Button */}
<button
type="button"
onClick={() => handleAddSize(colorIndex)}
className="mt-2 flex items-center rounded-md bg-blue-500 px-3 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={16} />
Add Size
</button>
</div>
)}
</div>
))}
</div>
{/* Add Color Button */}
<button
type="button"
onClick={handleAddColor}
className="mt-4 flex items-center rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={20} />
Add Color
</button>
</div>
)}
{/* Has Size (when no color) */}
{!editedProduct.has_color && (
<div className="flex items-center">
<input
type="checkbox"
id="has_size"
checked={editedProduct.has_size}
onChange={() =>
setEditedProduct((prev) => ({
...prev,
has_size: !prev.has_size,
sizes: prev.has_size ? [] : prev.sizes,
}))
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_size" className="ml-2 text-sm font-medium text-gray-700">
Has Size?
</label>
</div>
)}
{/* Sizes (when no color) */}
{!editedProduct.has_color && editedProduct.has_size && (
<div className="mt-4 space-y-4">
{editedProduct.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="rounded-md border p-4">
{/* Size Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Size Name
</label>
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "name", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteSize(-1, sizeIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Size"
>
<Trash2 size={16} />
</button>
</div>
{/* Size Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={size.price || ""}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "price", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={size.qty || ""}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "qty", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{sizeIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={size.inheritImages || false}
onChange={() =>
handleInheritImagesChange("size", -1, sizeIndex)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous size
</label>
</div>
)}
{/* Image Uploader */}
{!size.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", -1, sizeIndex)
}
existingImages={size.images}
/>
</div>
)}
</div>
))}
{/* Add Size Button */}
<button
type="button"
onClick={() => handleAddSize(-1)}
className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={20} />
Add Size
</button>
</div>
)}
{/* Submit Button */}
<div className="flex justify-end">
<button
type="submit"
className="flex items-center rounded-md bg-green-500 px-6 py-3 text-white hover:bg-green-600"
>
<Edit className="mr-2" size={20} />
Save Changes
</button>
</div>
</form>
</div>
</div>
);
};
export default EditProduct;
c. components/AddProductDialog.jsx
// components/AddProductDialog.jsx
"use client";
import React, { useState, useEffect } from "react";
import { X, Plus, Trash2 } from "lucide-react";
import MultipartFileUploader from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import { getToken } from "@/app/auth";
const AddProductDialog = ({ isOpen, onClose, onProductAdded }) => {
const [product, setProduct] = useState({
name: "",
description: "",
brand_id: "",
has_color: false,
colors: [],
has_size: false,
sizes: [],
categories: [],
price: "",
qty: "",
images: [],
});
const [categories, setCategories] = useState([]);
const [brands, setBrands] = useState([]);
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
fetchCategories();
fetchBrands();
}, []);
const fetchCategories = async () => {
try {
const token = getToken(); // Retrieve the token from localStorage
if (!token) {
toast.error("You must be logged in to add a product.");
return;
}
const response = await fetch(
"http://localhost:4000/subcategories/non-brands",
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
}
);
const data = await response.json();
setCategories(data);
} catch (error) {
console.error("Error fetching categories:", error);
}
};
const fetchBrands = async () => {
try {
const token = getToken(); // Retrieve the token from localStorage
if (!token) {
toast.error("You must be logged in to add a product.");
return;
}
const response = await fetch("http://localhost:4000/subcategories/brands", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
setBrands(data);
} catch (error) {
console.error("Error fetching brands:", error);
}
};
const handleCategoryToggle = (categoryId) => {
setProduct((prevProduct) => {
const updatedCategories = prevProduct.categories.includes(categoryId)
? prevProduct.categories.filter((id) => id !== categoryId)
: [...prevProduct.categories, categoryId];
return { ...prevProduct, categories: updatedCategories };
});
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setProduct((prevProduct) => ({
...prevProduct,
[name]: value,
}));
};
const handleBrandChange = (e) => {
setProduct((prevProduct) => ({
...prevProduct,
brand_id: parseInt(e.target.value),
}));
};
const handleAddColor = () => {
setProduct((prevProduct) => ({
...prevProduct,
colors: [
...prevProduct.colors,
{ name: "", price: null, qty: null, sizes: [], images: [] },
],
}));
};
const handleAddSize = (colorIndex) => {
setProduct((prevProduct) => {
if (colorIndex === -1) {
return {
...prevProduct,
sizes: [
...prevProduct.sizes,
{ name: "", price: "", qty: "", images: [] },
],
};
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes.push({
name: "",
price: "",
qty: "",
images: [],
});
return {
...prevProduct,
colors: newColors,
};
}
});
};
const handleColorChange = (index, field, value) => {
setProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors[index] = {
...newColors[index],
[field]: value,
};
return { ...prevProduct, colors: newColors };
});
};
const handleSizeChange = (colorIndex, sizeIndex, field, value) => {
setProduct((prevProduct) => {
if (colorIndex === -1) {
const newSizes = [...prevProduct.sizes];
newSizes[sizeIndex] = {
...newSizes[sizeIndex],
[field]: value,
images: newSizes[sizeIndex].images || [],
};
return { ...prevProduct, sizes: newSizes };
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes[sizeIndex] = {
...newColors[colorIndex].sizes[sizeIndex],
[field]: value,
images: newColors[colorIndex].sizes[sizeIndex].images || [],
};
return { ...prevProduct, colors: newColors };
}
});
};
const handleImageUpload = (fileIds, variantType, colorIndex, sizeIndex) => {
setProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (variantType === "color") {
updatedProduct.colors[colorIndex].images = fileIds;
} else if (variantType === "size") {
if (colorIndex === -1) {
updatedProduct.sizes[sizeIndex].images = fileIds;
} else {
updatedProduct.colors[colorIndex].sizes[sizeIndex].images = fileIds;
}
} else {
updatedProduct.images = fileIds;
}
return updatedProduct;
});
};
const handleInheritImagesChange = (variantType, colorIndex, sizeIndex) => {
setProduct((prevProduct) => {
const updatedProduct = JSON.parse(JSON.stringify(prevProduct)); // Deep clone
if (variantType === "color") {
updatedProduct.colors[colorIndex].inheritImages =
!updatedProduct.colors[colorIndex].inheritImages;
if (
updatedProduct.colors[colorIndex].inheritImages &&
colorIndex > 0
) {
const prevColor = updatedProduct.colors[colorIndex - 1];
updatedProduct.colors[colorIndex].images = [...prevColor.images];
}
} else if (variantType === "size") {
if (colorIndex === -1) {
updatedProduct.sizes[sizeIndex].inheritImages =
!updatedProduct.sizes[sizeIndex].inheritImages;
if (
updatedProduct.sizes[sizeIndex].inheritImages &&
sizeIndex > 0
) {
const prevSize = updatedProduct.sizes[sizeIndex - 1];
updatedProduct.sizes[sizeIndex].images = [...prevSize.images];
}
} else {
updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages =
!updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages;
if (
updatedProduct.colors[colorIndex].sizes[sizeIndex].inheritImages &&
sizeIndex > 0
) {
const prevSize = updatedProduct.colors[colorIndex].sizes[sizeIndex - 1];
updatedProduct.colors[colorIndex].sizes[sizeIndex].images = [
...prevSize.images,
];
}
}
}
return updatedProduct;
});
};
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
// Determine productType based on the presence of colors and sizes
let productType;
if (product.has_color && product.has_size) {
productType = "color_size";
} else if (product.has_color) {
productType = "color";
} else if (product.has_size) {
productType = "size";
} else {
productType = "simple";
}
// Construct productData
const productData = {
...product,
product_type: productType,
category_ids: product.categories,
has_color: product.has_color,
has_size: product.has_size,
colors: product.has_color
? product.colors.map((color) => ({
name: color.name,
price: color.price ? parseFloat(color.price) : null,
qty: color.qty ? parseInt(color.qty) : null,
hasSize: product.has_size,
sizes: product.has_size
? color.sizes.map((size) => ({
name: size.name,
price: parseFloat(size.price),
qty: parseInt(size.qty),
images: size.images,
}))
: [],
images: color.images,
}))
: [],
sizes:
product.has_size && !product.has_color
? product.sizes.map((size) => ({
name: size.name,
price: parseFloat(size.price),
qty: parseInt(size.qty),
images: size.images,
}))
: [],
price: product.price ? parseFloat(product.price) : null,
qty: product.qty ? parseInt(product.qty) : null,
images: product.images,
};
const token = getToken();
if (!token) {
setIsSubmitting(false);
toast.error("You must be logged in to add a product.");
return;
}
try {
const response = await fetch("http://localhost:4000/products", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(productData),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Failed to create product");
}
const newProduct = await response.json();
onProductAdded(newProduct);
toast.success("Product added successfully!");
// Reset the form after successful submission
setProduct({
name: "",
description: "",
brand_id: "",
has_color: false,
colors: [],
has_size: false,
sizes: [],
categories: [],
price: "",
qty: "",
images: [],
});
onClose();
} catch (error) {
console.error("Error creating product:", error);
toast.error(`Error: ${error.message}`);
} finally {
setIsSubmitting(false);
}
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 overflow-y-auto">
<div className="relative w-full max-w-3xl bg-white rounded-lg p-8 shadow-lg">
{/* Close Button */}
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
>
<X size={24} />
</button>
<h2 className="mb-6 text-2xl font-bold">Add New Product</h2>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Product Name */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="name">
Product Name
</label>
<input
type="text"
id="name"
name="name"
value={product.name}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
{/* Description */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="description">
Description
</label>
<textarea
id="description"
name="description"
value={product.description}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
rows={4}
style={{ direction: "rtl" }}
required
></textarea>
</div>
{/* Categories */}
<div>
<label className="block text-sm font-semibold text-gray-700">Categories</label>
<div className="mt-2 flex flex-wrap gap-2">
{categories.map((category) => (
<button
key={category.id}
type="button"
onClick={() => handleCategoryToggle(category.id)}
className={`rounded-full px-4 py-2 text-sm ${
product.categories.includes(category.id)
? "bg-blue-500 text-white"
: "bg-gray-200 text-gray-700"
}`}
>
{category.name}
</button>
))}
</div>
</div>
{/* Brand */}
<div>
<label className="block text-sm font-semibold text-gray-700" htmlFor="brand">
Brand
</label>
<select
id="brand"
name="brand"
value={product.brand_id}
onChange={handleBrandChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
>
<option value="">Select a brand</option>
{brands.map((brand) => (
<option key={brand.id} value={brand.id}>
{brand.name}
</option>
))}
</select>
</div>
{/* Has Color */}
<div className="flex items-center">
<input
type="checkbox"
id="has_color"
checked={product.has_color}
onChange={() =>
setProduct((prev) => ({
...prev,
has_color: !prev.has_color,
colors: prev.has_color ? [] : prev.colors,
}))
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_color" className="ml-2 text-sm font-medium text-gray-700">
Has Color?
</label>
</div>
{/* Colors */}
{product.has_color && (
<div className="mt-4">
<label className="block text-sm font-semibold text-gray-700">Colors</label>
<div className="mt-2 space-y-4">
{product.colors.map((color, colorIndex) => (
<div key={colorIndex} className="rounded-md border p-4">
{/* Color Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Color Name
</label>
<input
type="text"
value={color.name}
onChange={(e) =>
handleColorChange(colorIndex, "name", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteColor(colorIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Color"
>
<Trash2 size={16} />
</button>
</div>
{/* Color Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={color.price || ""}
onChange={(e) =>
handleColorChange(colorIndex, "price", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={color.qty || ""}
onChange={(e) =>
handleColorChange(colorIndex, "qty", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{colorIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={color.inheritImages || false}
onChange={() =>
handleInheritImagesChange("color", colorIndex, null)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous color
</label>
</div>
)}
{/* Image Uploader */}
{!color.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "color", colorIndex, null)
}
existingImages={color.images}
/>
</div>
)}
{/* Has Size */}
{product.has_size && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
id={`has_size_${colorIndex}`}
checked={color.hasSize || false}
onChange={() => {
setProduct((prev) => {
const newColors = [...prev.colors];
newColors[colorIndex].hasSize = !newColors[colorIndex].hasSize;
newColors[colorIndex].sizes = newColors[colorIndex].hasSize
? newColors[colorIndex].sizes
: [];
return { ...prev, colors: newColors };
});
}}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label
htmlFor={`has_size_${colorIndex}`}
className="ml-2 text-sm font-medium text-gray-700"
>
Has Size?
</label>
</div>
)}
{/* Sizes */}
{product.has_size && color.hasSize && (
<div className="mt-4 space-y-4">
{color.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="rounded-md border p-4">
{/* Size Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Size Name
</label>
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"name",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteSize(colorIndex, sizeIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Size"
>
<Trash2 size={16} />
</button>
</div>
{/* Size Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={size.price || ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"price",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={size.qty || ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"qty",
e.target.value
)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{sizeIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={size.inheritImages || false}
onChange={() =>
handleInheritImagesChange(
"size",
colorIndex,
sizeIndex
)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous size
</label>
</div>
)}
{/* Image Uploader */}
{!size.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(
fileIds,
"size",
colorIndex,
sizeIndex
)
}
existingImages={size.images}
/>
</div>
)}
</div>
))}
{/* Add Size Button */}
<button
type="button"
onClick={() => handleAddSize(colorIndex)}
className="flex items-center rounded-md bg-blue-500 px-3 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={16} />
Add Size
</button>
</div>
)}
</div>
))}
</div>
{/* Add Color Button */}
<button
type="button"
onClick={handleAddColor}
className="mt-4 flex items-center rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={20} />
Add Color
</button>
</div>
)}
{/* Has Size (when no color) */}
{!product.has_color && (
<div className="flex items-center">
<input
type="checkbox"
id="has_size"
checked={product.has_size}
onChange={() =>
setProduct((prev) => ({
...prev,
has_size: !prev.has_size,
sizes: prev.has_size ? [] : prev.sizes,
}))
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_size" className="ml-2 text-sm font-medium text-gray-700">
Has Size?
</label>
</div>
)}
{/* Sizes (when no color) */}
{!product.has_color && product.has_size && (
<div className="mt-4 space-y-4">
{product.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="rounded-md border p-4">
{/* Size Header */}
<div className="flex items-center justify-between">
<div className="flex-1">
<label className="block text-sm font-medium text-gray-700">
Size Name
</label>
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "name", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<button
type="button"
onClick={() => handleDeleteSize(-1, sizeIndex)}
className="ml-4 flex-shrink-0 rounded-full bg-red-500 p-2 text-white hover:bg-red-600"
title="Delete Size"
>
<Trash2 size={16} />
</button>
</div>
{/* Size Price and Quantity */}
<div className="mt-4 grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
value={size.price || ""}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "price", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
value={size.qty || ""}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "qty", e.target.value)
}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
/>
</div>
</div>
{/* Inherit Images */}
{sizeIndex > 0 && (
<div className="mt-4 flex items-center">
<input
type="checkbox"
checked={size.inheritImages || false}
onChange={() =>
handleInheritImagesChange("size", -1, sizeIndex)
}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label className="ml-2 text-sm font-medium text-gray-700">
Inherit images from previous size
</label>
</div>
)}
{/* Image Uploader */}
{!size.inheritImages && (
<div className="mt-4">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", -1, sizeIndex)
}
existingImages={size.images}
/>
</div>
)}
</div>
))}
{/* Add Size Button */}
<button
type="button"
onClick={() => handleAddSize(-1)}
className="flex items-center rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-2" size={20} />
Add Size
</button>
</div>
)}
{/* Product Price and Quantity (when no color and no size) */}
{!product.has_color && !product.has_size && (
<div className="mt-4 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700">
Price
</label>
<input
type="number"
name="price"
value={product.price}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Price"
min="0"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700">
Quantity
</label>
<input
type="number"
name="qty"
value={product.qty}
onChange={handleInputChange}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Quantity"
min="0"
required
/>
</div>
</div>
{/* Image Uploader */}
<div>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "product", null, null)
}
existingImages={product.images}
/>
</div>
</div>
)}
{/* Submit Button */}
<div className="flex justify-end">
<button
type="submit"
disabled={isSubmitting}
className={`flex items-center rounded-md bg-green-500 px-6 py-3 text-white hover:bg-green-600 ${
isSubmitting ? "opacity-50 cursor-not-allowed" : ""
}`}
>
<Plus className="mr-2" size={20} />
{isSubmitting ? "Adding..." : "Add Product"}
</button>
</div>
</form>
</div>
</div>
);
};
export default AddProductDialog;
3. Additional Recommendations
a. Optimize Image Loading
Ensure that images are optimized for web to improve load times. Utilize Next.js's built-in image optimization by properly configuring the next.config.js if not already done.
b. Error Handling Enhancements
Enhance error handling to provide more granular feedback. For instance, display specific error messages returned from the API.
c. Accessibility Improvements
Ensure all interactive elements are accessible:
- Use
aria-labels where necessary.
- Ensure sufficient color contrast.
- Make sure forms are navigable via keyboard.
d. Reusable Components
Consider creating reusable sub-components for repetitive structures like Color and Size sections to make the code more DRY (Don't Repeat Yourself).
e. State Management Optimization
If the application grows in complexity, consider using state management libraries like Redux or Context API for better state handling across components.
4. Conclusion
The above modifications convert your components from TypeScript to JavaScript, fix the issue with sizes nested within colors in the EditProduct component, enhance the UI/UX with Tailwind CSS, improve font usage, optimize for performance, and ensure responsiveness across devices. Make sure to thoroughly test these changes in your development environment to ensure they integrate seamlessly with your backend and existing application structure.
If you encounter any further issues or need additional enhancements, feel free to ask!