Enhance the ui/ux of edit product... improve the font… · The Chat Archive
Explore Enhance the ui/ux of edit product... improve the font, colors and everything... fix the… Save Share Download ▾ ReportEnhance the ui/ux of edit product... improve the font, colors and everything... fix the typescripts errors between editproduct and productspage... make the design responsive. Also there is a bug where editing product doesn't show the sizes inside the color...
editproducts doesn't have typescript errors now and it shouldn't!!!
it has only this:
TS71007: Props must be serializable for components in the "use client" entry file, "onClose" is invalid.
productspage have this: TS2322: Type 'import("/home/mustafakareem04/Downloads/free-nextjs-admin-dashboard-main/src/components/types").Product' is not assignable to type 'Product'.Types of property 'colors' are incompatible.Type 'import("/home/mustafakareem04/Downloads/free-nextjs-admin-dashboard-main/src/components/types").Color[]' is not assignable to type 'Color[]'.Type 'import("/home/mustafakareem04/Downloads/free-nextjs-admin-dashboard-main/src/components/types").Color' is not assignable to type 'Color'.Types of property 'price' are incompatible.Type 'number | null' is not assignable to type 'string | null'.Type 'number' is not assignable to type 'string'.
example of json response:
{"products":[{"id":683,"name":"Creat 3D Whitestrip Superme Bright","description":"لصقات تبييض الاسنان مع كرست بخطوات سهلة وسريعة للحصول على ابتسامة ناصعة البياض\n-تتكون من عامل التبييض الآمن بالمينا\n-تقنية خالية من الانزلاق تظل ثابتة.\n-سهل الاستخدام للغاية يمكنك التبييض أثناء المشي والتحدث والعمل وحتى شرب الماء\n-طريقة الاستخدام:\nتستخدم مرة واحدة يوميا على اسنان نظيفة ضعي الشرائح على الفك العلوي والسفلي وازيليها بعد 45 دقيقة","brand_id":225,"has_color":false,"has_size":true,"product_type":"size","price":0,"qty":0,"sold":0,"created_at":"2024-09-09T09:40:47.835Z","updated_at":"2024-09-14T11:27:34.532Z","categories":[{"id":226,"name":"Teeth","main_category_id":23,"main_category_name":"Mouth Care"}],"colors":[],"sizes":[{"id":1258,"name":"1 strip","price":5000,"qty":76,"sold":0,"color_id":null,"images":["1795.webp"]},{"id":1259,"name":"20 strips","price":90000,"qty":5,"sold":0,"color_id":null,"images":[]}],"images":[{"id":2172,"url":"1795.webp","color_id":null,"size_id":1258}]},{"id":1237,"name":"test","description":"test","brand_id":73,"has_color":true,"has_size":false,"product_type":"color_size","price":0,"qty":0,"sold":0,"created_at":"2024-09-25T08:05:58.982Z","updated_at":"2024-09-25T08:05:58.982Z","categories":[{"id":178,"name":"Body Cleansers","main_category_id":2,"main_category_name":"Body Care"}],"colors":[{"id":57,"name":"green","price":50000,"qty":9,"sold":0,"has_size":false,"sizes":[],"images":[]},{"id":56,"name":"red","price":0,"qty":0,"sold":0,"has_size":true,"sizes":[{"id":3013,"name":"20ml","price":15000,"qty":10,"sold":0,"color_id":56,"images":["3066.jpg"]},{"id":3014,"name":"30ml","price":40000,"qty":2,"sold":0,"color_id":56,"images":["3066.jpg"]}],"images":["3066.jpg"]}],"sizes":[],"images":[{"id":199,"url":"3066.jpg","color_id":56,"size_id":3013},{"id":200,"url":"3066.jpg","color_id":56,"size_id":3014}]}],"total":2,"page":1,"itemsPerPage":15,"totalPages":1,"hasMore":false,"minPrice":0,"maxPrice":250000}
updateProduct in the backend:
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData: UpdateProductInput = req.body;
const productId: number = parseInt(id, 10);
Show full message · 1,934 lines Assistant2024-09-25 11:43 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Sep 25, 2024
Added to archive Nov 16, 2026
ID 01m7h41vydqcwrr23m1zv9a9ddSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: a271b5f811a3691ba195359d2f370520
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
code Copy code
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
await query('BEGIN');
// Adjust product price if necessary
let adjustedProductPrice: number = productData.price;
if (adjustedProductPrice < 1000) {
adjustedProductPrice = parseFloat((adjustedProductPrice * 1000).toFixed(2));
}
// Update product details
const result = await query(
`
UPDATE products
SET
name = $1,
description = $2,
brand_id = $3,
has_color = $4,
has_size = $5,
product_type = $6,
price = $7,
qty = $8,
updated_at = CURRENT_TIMESTAMP
WHERE id = $9
RETURNING *
`,
[
productData.name,
productData.description,
productData.brand_id,
productData.has_color,
productData.has_size,
productData.product_type,
adjustedProductPrice,
productData.qty,
productId
]
);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete existing category associations
await query('DELETE FROM product_categories WHERE product_id = $1', [productId]);
// Determine if images are provided in the update
const hasMainImagesInUpdate = productData.images !== undefined && productData.images !== null;
// Handle Images
let insertedImages: Image[] = [];
if (hasMainImagesInUpdate) {
// Delete existing main images
await query('DELETE FROM images WHERE product_id = $1 AND color_id IS NULL AND size_id IS NULL', [productId]);
// Insert new main images if provided
if (productData.images.length > 0) {
const imagesInsertPromises = productData.images.map((image: ImageInput) =>
query(
`INSERT INTO images (product_id, url, color_id, size_id)
VALUES ($1, $2, $3, $4)
RETURNING id, url, color_id, size_id`,
[productId, image.url, image.color_id || null, image.size_id || null]
)
);
const insertedImagesResults = await Promise.all(imagesInsertPromises);
insertedImages = insertedImagesResults.map((imgResult: any) => ({
id: imgResult.rows[0].id,
url: imgResult.rows[0].url,
color_id: imgResult.rows[0].color_id,
size_id: imgResult.rows[0].size_id
}));
}
} else {
// If images are not provided, fetch existing main images
const existingImagesResult = await query(
`SELECT id, url, color_id, size_id FROM images
WHERE product_id = $1 AND color_id IS NULL AND size_id IS NULL`,
[productId]
);
insertedImages = existingImagesResult.rows.map((row: any) => ({
id: row.id,
url: row.url,
color_id: row.color_id,
size_id: row.size_id
}));
}
// Insert category associations
if (productData.category_ids.length > 0) {
const categoryInsertPromises = productData.category_ids.map((categoryId: number) =>
query(
`INSERT INTO product_categories (product_id, category_id)
VALUES ($1, $2)`,
[productId, categoryId]
)
);
await Promise.all(categoryInsertPromises);
}
// Insert or Update Colors and Sizes
let insertedColors: number[] = [];
let insertedSizes: number[] = [];
if (productData.has_color && productData.colors && productData.colors.length > 0) {
for (const colorInput of productData.colors) {
// Adjust color price if necessary
let adjustedColorPrice: number = colorInput.price;
if (adjustedColorPrice < 1000) {
adjustedColorPrice = parseFloat((adjustedColorPrice * 1000).toFixed(2));
}
// Insert or Update color
let colorId: number;
if (colorInput.id) {
// Update existing color
await query(
`
UPDATE colors
SET
name = $1,
price = $2,
qty = $3,
sold = $4,
has_size = $5
WHERE id = $6
`,
[
colorInput.name,
adjustedColorPrice,
colorInput.qty,
colorInput.sold || 0,
colorInput.has_size,
colorInput.id
]
);
colorId = colorInput.id;
} else {
// Insert new color
const colorResult = await query(
`
INSERT INTO colors
(product_id, name, price, qty, sold, has_size)
VALUES
($1, $2, $3, $4, 0, $5)
RETURNING id
`,
[productId, colorInput.name, adjustedColorPrice, colorInput.qty, colorInput.has_size]
);
colorId = colorResult.rows[0].id;
insertedColors.push(colorId);
}
// Handle Color Images
const hasColorImagesInUpdate = colorInput.images !== undefined && colorInput.images !== null;
if (hasColorImagesInUpdate) {
// Delete existing images for this color
await query('DELETE FROM images WHERE product_id = $1 AND color_id = $2 AND size_id IS NULL', [productId, colorId]);
// Insert new images if provided
if (colorInput.images.length > 0) {
const colorImagesInsertPromises = colorInput.images.map((image: ImageInput) =>
query(
`INSERT INTO images (product_id, color_id, url, size_id)
VALUES ($1, $2, $3, $4)
RETURNING id, url, color_id, size_id`,
[productId, colorId, image.url, image.size_id || null]
)
);
await Promise.all(colorImagesInsertPromises);
// Optionally, store or handle color images if needed
}
} else {
// Fetch existing color images
await query(
SELECT id, url, color_id, size_id FROM images WHERE product_id = $1 AND color_id = $2 AND size_id IS NULL,
[productId, colorId]
);
}
code Copy code
// Handle Sizes within Color
if (colorInput.has_size && colorInput.sizes && colorInput.sizes.length > 0) {
for (const sizeInput of colorInput.sizes) {
// Adjust size price if necessary
let adjustedSizePrice: number = sizeInput.price;
if (adjustedSizePrice < 1000) {
adjustedSizePrice = parseFloat((adjustedSizePrice * 1000).toFixed(2));
}
// Insert or Update size
let sizeId: number;
if (sizeInput.id) {
// Update existing size
await query(
`
UPDATE sizes
SET
name = $1,
price = $2,
qty = $3,
sold = $4,
color_id = $5
WHERE id = $6
`,
[
sizeInput.name,
adjustedSizePrice,
sizeInput.qty,
sizeInput.sold || 0,
colorId,
sizeInput.id
]
);
sizeId = sizeInput.id;
} else {
// Insert new size
const sizeResult = await query(
`
INSERT INTO sizes
(product_id, color_id, name, price, qty, sold)
VALUES
($1, $2, $3, $4, $5, 0)
RETURNING id
`,
[productId, colorId, sizeInput.name, adjustedSizePrice, sizeInput.qty]
);
sizeId = sizeResult.rows[0].id;
insertedSizes.push(sizeId);
}
// Handle Size Images
const hasSizeImagesInUpdate = sizeInput.images !== undefined && sizeInput.images !== null;
if (hasSizeImagesInUpdate) {
// Delete existing images for this size
await query('DELETE FROM images WHERE product_id = $1 AND size_id = $2', [productId, sizeId]);
// Insert new images if provided
if (sizeInput.images.length > 0) {
const sizeImagesInsertPromises = sizeInput.images.map((image: ImageInput) =>
query(
`INSERT INTO images (product_id, size_id, url)
VALUES ($1, $2, $3)
RETURNING id, url, color_id, size_id`,
[productId, sizeId, image.url]
)
);
await Promise.all(sizeImagesInsertPromises);
// Optionally, store or handle size images if needed
}
} else {
// Fetch existing size images
await query(
SELECT id, url, color_id, size_id FROM images WHERE product_id = $1 AND size_id = $2,
[productId, sizeId]
);
}
}
}
}
} else if (productData.has_size && productData.sizes && productData.sizes.length > 0) {
for (const sizeInput of productData.sizes) {
// Adjust size price if necessary
let adjustedSizePrice: number = sizeInput.price;
if (adjustedSizePrice < 1000) {
adjustedSizePrice = parseFloat((adjustedSizePrice * 1000).toFixed(2));
}
code Copy code
// Insert or Update size
let sizeId: number;
if (sizeInput.id) {
// Update existing size
await query(
`
UPDATE sizes
SET
name = $1,
price = $2,
qty = $3,
sold = $4
WHERE id = $5
`,
[
sizeInput.name,
adjustedSizePrice,
sizeInput.qty,
sizeInput.sold || 0,
sizeInput.id
]
);
sizeId = sizeInput.id;
} else {
// Insert new size
const sizeResult = await query(
`
INSERT INTO sizes
(product_id, name, price, qty, sold)
VALUES
($1, $2, $3, $4, 0)
RETURNING id
`,
[productId, sizeInput.name, adjustedSizePrice, sizeInput.qty]
);
sizeId = sizeResult.rows[0].id;
insertedSizes.push(sizeId);
}
// Handle Size Images
const hasSizeImagesInUpdate = sizeInput.images !== undefined && sizeInput.images !== null;
if (hasSizeImagesInUpdate) {
// Delete existing images for this size
await query('DELETE FROM images WHERE product_id = $1 AND size_id = $2', [productId, sizeId]);
// Insert new images if provided
if (sizeInput.images.length > 0) {
const sizeImagesInsertPromises = sizeInput.images.map((image: ImageInput) =>
query(
`INSERT INTO images (product_id, size_id, url)
VALUES ($1, $2, $3)
RETURNING id, url, color_id, size_id`,
[productId, sizeId, image.url]
)
);
await Promise.all(sizeImagesInsertPromises);
// Optionally, store or handle size images if needed
}
} else {
// Fetch existing size images
code Copy code
}
}
}
// Fetch and populate categories with details
const categories = await fetchCategoryDetails(productData.category_ids);
// Fetch existing images if not updated
if (!hasMainImagesInUpdate) {
const existingImagesResult = await query(
`SELECT id, url, color_id, size_id FROM images
WHERE product_id = $1 AND color_id IS NULL AND size_id IS NULL`,
[productId]
);
insertedImages = existingImagesResult.rows.map((row: any) => ({
id: row.id,
url: row.url,
color_id: row.color_id,
size_id: row.size_id
}));
}
// Construct the updated product object as it would appear in the cache
const updatedProduct: Product = {
id: productId,
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.has_color,
has_size: productData.has_size,
product_type: productData.product_type,
price: adjustedProductPrice,
qty: productData.qty,
sold: 0, // Assuming sold remains unchanged; adjust if necessary
created_at: result.rows[0].created_at.toISOString(),
updated_at: new Date().toISOString(),
categories: categories,
colors: productData.has_color && productData.colors
? productData.colors.map((colorInput, index) => ({
id: colorInput.id || insertedColors[index],
name: colorInput.name,
price: colorInput.price || 0,
qty: colorInput.qty,
sold: colorInput.sold || 0,
has_size: colorInput.has_size,
sizes: colorInput.has_size && colorInput.sizes
? colorInput.sizes.map((sizeInput, sIndex) => ({
id: sizeInput.id || insertedSizes[sIndex],
name: sizeInput.name,
price: sizeInput.price,
qty: sizeInput.qty,
sold: sizeInput.sold || 0,
color_id: colorInput.id || insertedColors[index],
images: sizeInput.images ? sizeInput.images.map(img => img.url) : []
}))
: [],
images: colorInput.images ? colorInput.images.map(img => img.url) : []
}))
: [],
sizes: productData.has_size && !productData.has_color && productData.sizes
? productData.sizes.map((sizeInput, index) => ({
id: sizeInput.id || insertedSizes[index],
name: sizeInput.name,
price: sizeInput.price,
qty: sizeInput.qty,
sold: sizeInput.sold || 0,
color_id: null,
images: sizeInput.images ? sizeInput.images.map(img => img.url) : []
}))
: [],
images: insertedImages
};
// Update the cache
updateProductInCache(updatedProduct);
await query('COMMIT');
res.json({ message: 'Product updated successfully', product: updatedProduct });
} catch (error) {
await query('ROLLBACK');
console.error('Error updating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
ProductsPage:
// pages/products.tsx
"use client";
import React, {
useState,
useEffect,
useCallback,
useMemo,
ChangeEvent,
} 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"; // Ensure this component matches the one in OrdersPage
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import debounce from "lodash/debounce";
import { getToken } from "@/app/auth";
import {
Product,
Brand,
ApiResponse,
Category,
Color,
Size,
} from "@/components/types";
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString(); // 'MM/DD/YYYY' format
};
const PRODUCTS_PER_PAGE = 15; // Adjusted as per JSON response's itemsPerPage
const ProductsPage: React.FC = () => {
// State Variables
const [products, setProducts] = useState<Product[]>([]);
const [brands, setBrands] = useState<Brand[]>([]);
const [brandMap, setBrandMap] = useState<{ [key: number]: string }>({});
const [currentPage, setCurrentPage] = useState(1);
const [searchTerm, setSearchTerm] = useState("");
const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
const [sortBy, setSortBy] = useState("created_at");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [isAddProductDialogOpen, setIsAddProductDialogOpen] =
useState(false);
const [isEditProductDialogOpen, setIsEditProductDialogOpen] =
useState(false);
const [productToEdit, setProductToEdit] = useState<Product | null>(null);
const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] =
useState(false);
const [productToDelete, setProductToDelete] = useState<Product | null>(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: string) => {
setSearchTerm(term);
setCurrentPage(1);
}, 300),
[],
);
useEffect(() => {
debouncedSearch(searchInput);
return () => {
debouncedSearch.cancel();
};
}, [searchInput, debouncedSearch]);
const handleSearchChange = (e: ChangeEvent) => {
setSearchInput(e.target.value);
};
// Fetch Brand Details
const fetchBrands = useCallback(async () => {
const token = getToken(); // Retrieve the token from localStorage
code Copy code
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}`, // Include the token here
},
},
);
if (!response.ok) {
throw new Error("Failed to fetch brands");
}
const data: Brand[] = await response.json();
setBrands(data);
// Create a mapping from brand_id to brand_name for easy lookup
const map: { [key: number]: string } = {};
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
code Copy code
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}`, // Include the token here
},
},
);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data: ApiResponse = 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: Product) => {
setProductToEdit(product);
setIsEditProductDialogOpen(true);
}, []);
const handleDeleteClick = useCallback((product: Product) => {
setProductToDelete(product);
setIsDeleteConfirmOpen(true);
}, []);
const handleDeleteConfirm = useCallback(async () => {
if (productToDelete) {
setIsDeleting(true);
const token = getToken(); // the token from localStorage
code Copy code
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}`, // Include the token here
},
},
);
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);
}
}
// Helper function to get the first color's first size information
const getFirstColorSizeInfo = useCallback((product: 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: Product): string => {
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: Product): number | string => {
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: Product): number => {
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: number) => {
setCurrentPage(newPage);
window.scrollTo({ top: 0, behavior: "smooth" });
}, []);
return (
Products - Naay Store
{/* Link to a better font, e.g., Inter from Google Fonts */}
code Copy code
<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 as keyof Product)}
>
<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 as "asc" | "desc")}
>
<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 /> {/* Same loader as OrdersPage */}
</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);
// Remove displaying unnecessary fields like id and product_type
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 px-4 py-2 text-white transition duration-300 hover:bg-danger"
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: Product) => {
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: Product) => {
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 px-4 py-2 text-white transition duration-300 hover:bg-danger"
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);
EditProducts:
"use client";
import { X, Plus, Trash2 } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import React, { useEffect, useState } from "react";
import { getToken } from "@/app/auth";
interface Category {
id: number;
name: string;
}
interface EditProductProps {
isOpen: boolean;
onClose: () => void;
product: Product;
}
interface Brand {
id: number;
name: string;
}
interface Size {
id?: number;
name: string;
price: string;
qty: string;
images: string[];
inheritImages?: boolean;
}
interface Color {
inheritImages?: boolean;
id?: number;
name: string;
price: string | null;
qty: string | null;
sizes: Size[];
images: string[];
}
interface Product {
id: number;
name: string;
description: string;
brand_id: number;
has_color: boolean;
has_size: boolean;
categories: Category[];
colors: Color[];
sizes: Size[];
price: string | null;
qty: string | null;
images: string[];
}
export default function EditProduct({
isOpen,
onClose,
product,
}: EditProductProps) {
const [editedProduct, setEditedProduct] = useState({
...product,
sizes: product.sizes || [], // Ensure sizes is always an array
colors: product.colors.map((color) => ({
...color,
sizes: color.sizes || [], // Ensure sizes is always an array for each color
})),
images: [],
});
const [categories, setCategories] = useState<Category[]>([]);
const [brands, setBrands] = useState<Brand[]>([]);
useEffect(() => {
fetchCategories();
fetchBrands();
}, []);
const handleDeleteColor = (colorIndex: number) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors.splice(colorIndex, 1);
return { ...prevProduct, colors: newColors };
});
};
const handleDeleteSize = (colorIndex: number, sizeIndex: number) => {
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: "color" | "size",
colorIndex: number,
sizeIndex: number,
) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
code Copy code
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 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 handleCategoryToggle = (categoryId: number) => {
// @ts-ignore
setEditedProduct((prevProduct) => {
const updatedCategories = prevProduct.categories.some(
// @ts-ignore
(cat) => cat.id === categoryId,
)
? prevProduct.categories.filter((cat) => {
// @ts-ignore
cat.id !== categoryId;
})
: [
...prevProduct.categories,
{
id: categoryId,
name: categories.find((cat) => cat.id === categoryId)?.name || "",
},
];
return { ...prevProduct, categories: updatedCategories };
});
};
const handleInputChange = (e: {
target: { name: string; value: string };
}) => {
const { name, value } = e.target;
setEditedProduct((prevProduct) => ({
...prevProduct,
[name]: value,
}));
};
const handleColorToggle = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
has_color: !prevProduct.has_color,
colors: !prevProduct.has_color ? [] : prevProduct.colors,
}));
};
const handleBrandChange = (e: React.ChangeEvent) => {
setEditedProduct((prevProduct) => ({
...prevProduct,
brand_id: parseInt(e.target.value),
}));
};
const handleSizeToggle = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
has_size: !prevProduct.has_size,
sizes: !prevProduct.has_size ? [] : prevProduct.sizes,
}));
};
const handleAddColor = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
colors: [
...prevProduct.colors,
{ name: "", price: null, qty: null, sizes: [], images: [] },
],
}));
};
const handleAddSize = (colorIndex: number) => {
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: number,
field: keyof Color,
value: string,
) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors[index] = {
...newColors[index],
[field]: value,
};
return { ...prevProduct, colors: newColors };
});
};
const handleSizeChange = (
colorIndex: number,
sizeIndex: number,
field: keyof Size,
value: string,
) => {
setEditedProduct((prevProduct) => {
if (colorIndex === -1) {
const newSizes = [...prevProduct.sizes];
newSizes[sizeIndex] = {
...newSizes[sizeIndex],
[field]: value,
images: newSizes[sizeIndex].images || [], // Ensure images array exists
};
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 || [], // Ensure images array exists
};
return { ...prevProduct, colors: newColors };
}
});
};
const handleImageUpload = (
fileIds: string[],
variantType: "color" | "size" | "product",
colorIndex: number,
sizeIndex: number,
) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
code Copy code
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: React.FormEvent) => {
e.preventDefault();
const productType =
editedProduct.has_color && editedProduct.has_size
? "color_size"
: editedProduct.has_color
? "color"
: editedProduct.has_size
? "size"
: "simple";
code Copy code
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, // Include the color ID if it exists
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, // Include the size ID if it exists
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, // Include the size ID if it exists
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}`, // Include the token here
},
body: JSON.stringify(productData),
},
);
if (!response.ok) {
throw new Error("Failed to update product");
}
const updatedProduct = await response.json();
console.log("Product updated:", updatedProduct);
toast.success("Product updated successfully!");
onClose();
} catch (error) {
console.error("Error updating product:", error);
toast.error("Failed to update product. Please try again.");
}
if (!isOpen) return null;
code Copy code
<h2 className="mb-6 text-2xl font-bold">Edit Product</h2>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Product Name */}
<div>
<label className="mb-2 block font-bold" htmlFor="name">
Product Name
</label>
<input
type="text"
id="name"
name="name"
value={editedProduct.name}
onChange={handleInputChange}
className="w-full rounded-md border p-2"
required
/>
</div>
{/* Description */}
<div>
<label className="mb-2 block font-bold" htmlFor="description">
Description
</label>
<textarea
id="description"
name="description"
value={editedProduct.description}
onChange={handleInputChange}
className="w-full rounded-md border p-2"
style={{ direction: "rtl" }}
required
/>
</div>
{/* Categories */}
<div>
<label className="mb-2 block font-bold">Categories</label>
<div className="flex flex-wrap gap-2">
{categories.map((category) => (
<button
key={category.id}
type="button"
onClick={() => handleCategoryToggle(category.id)}
className={`rounded-full px-3 py-1 text-sm ${
editedProduct.categories.some(
// @ts-ignore
(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="mb-2 block font-bold" htmlFor="brand">
Brand
</label>
<select
id="brand"
name="brand"
value={editedProduct.brand_id}
onChange={handleBrandChange}
className="w-full rounded-md border p-2"
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>
<label className="flex items-center">
<input
type="checkbox"
checked={editedProduct.has_color}
onChange={handleColorToggle}
className="mr-2"
/>
<span className="font-bold">Has Color?</span>
</label>
</div>
{/* Colors */}
{editedProduct.has_color && (
<div>
<label className="mb-2 block font-bold">Colors</label>
<div className="space-y-4">
{editedProduct.colors.map((color, colorIndex) => (
<div key={colorIndex} className="rounded-md border p-4">
<div className="mb-2 flex items-center justify-between">
<input
type="text"
value={color.name}
onChange={(e) =>
handleColorChange(colorIndex, "name", e.target.value)
}
className="mr-2 flex-grow rounded-md border p-2"
placeholder="Color name"
/>
<button
type="button"
onClick={() => handleDeleteColor(colorIndex)}
className="text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="mt-2 space-y-2">
<div className="flex space-x-2">
<input
type="number"
// @ts-ignore
value={color.price}
onChange={(e) =>
handleColorChange(
colorIndex,
"price",
e.target.value,
)
}
className="w-1/2 rounded-md border p-2"
placeholder="Price"
/>
<input
type="number"
// @ts-ignore
value={color.qty}
onChange={(e) =>
handleColorChange(colorIndex, "qty", e.target.value)
}
className="w-1/2 rounded-md border p-2"
placeholder="Quantity"
/>
</div>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
// @ts-ignore
handleImageUpload(fileIds, "color", colorIndex)
}
// @ts-ignore
existingImages={color.images}
/>
</div>
</div>
))}
</div>
<button
type="button"
onClick={handleAddColor}
className="mt-2 rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-1 inline-block" size={16} />
Add Color
</button>
</div>
)}
{/* Has Size */}
<div>
<label className="flex items-center">
<input
type="checkbox"
checked={editedProduct.has_size}
onChange={handleSizeToggle}
className="mr-2"
/>
<span className="font-bold">Has Size?</span>
</label>
</div>
{/* Sizes */}
{editedProduct.has_size && (
<div>
<label className="mb-2 block font-bold">Sizes</label>
<div className="space-y-2">
{editedProduct.sizes.map((size, index) => (
<div key={index} className="space-y-2 rounded-md border p-2">
<div className="flex items-center justify-between">
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(-1, index, "name", e.target.value)
}
className="mr-2 w-full rounded-md border p-2"
placeholder="Size name"
/>
<button
type="button"
onClick={() => handleDeleteSize(-1, index)}
className="text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="flex space-x-2">
<input
type="number"
value={size.price}
onChange={(e) =>
handleSizeChange(-1, index, "price", e.target.value)
}
className="w-1/2 rounded-md border p-2"
placeholder="Price"
/>
<input
type="number"
value={size.qty}
onChange={(e) =>
handleSizeChange(-1, index, "qty", e.target.value)
}
className="w-1/2 rounded-md border p-2"
placeholder="Quantity"
/>
</div>
{index > 0 && (
<label className="flex items-center">
<input
type="checkbox"
checked={size.inheritImages}
onChange={() =>
handleInheritImagesChange("size", -1, index)
}
className="mr-1"
/>
<span>Inherit images</span>
</label>
)}
{!size.inheritImages && (
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", -1, index)
}
/>
)}
</div>
))}
<button
type="button"
onClick={() => handleAddSize(-1)}
className="rounded-md bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
>
<Plus className="mr-1 inline-block" size={16} />
Add Size
</button>
</div>
</div>
)}
{/* Product Details (when no color and no size) */}
{!product.has_color && !product.has_size && (
<div>
<label className="mb-2 block font-bold">Product Details</label>
<div className="flex items-center space-x-2">
<input
type="number"
// @ts-ignore
value={product.price}
onChange={(e) =>
handleInputChange({
target: { name: "price", value: e.target.value },
})
}
className="rounded-md border p-2"
placeholder="Price"
/>
<input
type="number"
// @ts-ignore
value={product.qty}
onChange={(e) =>
handleInputChange({
target: { name: "qty", value: e.target.value },
})
}
className="rounded-md border p-2"
placeholder="Quantity"
/>
</div>
<div className="mt-2">
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
// @ts-ignore
handleImageUpload(fileIds, "product")
}
/>
</div>
</div>
)}
<div className="flex justify-end">
<button
type="submit"
className="rounded-md bg-green-500 px-4 py-2 text-white hover:bg-green-600"
>
Edit Product
</button>
</div>
</form>
</div>
</div>
types.ts:
// types.ts
export interface Size {
id: number;
name: string;
price: number;
qty: number;
sold: number;
color_id: number | null;
images: string[];
}
export interface Color {
id: number;
name: string;
price: number | null;
qty: number | null;
sold: number;
sizes: Size[];
images: string;
}
export interface ImageType {
id: number;
url: string;
color_id: number | null;
size_id: number | null;
}
export interface Category {
id: number;
name: string;
main_category_id: number;
main_category_name: string;
}
export interface Product {
id: number;
name: string;
description: string;
brand_id: number;
has_color: boolean;
has_size: boolean;
product_type: string;
price: number;
qty: number;
sold: number;
created_at: string;
updated_at: string;
categories: Category[];
colors: Color[];
sizes: Size[];
images: ImageType[];
}
export interface ApiResponse {
products: Product[];
total: number;
page: number;
itemsPerPage: number;
totalPages: number;
hasMore: boolean;
}
export interface Brand {
id: number;
name: string;
}
Make the editproduct page smooth and flewless... the user experience should priority... also improve the font because it is not good now...
To enhance the UI/UX of your EditProduct and ProductsPage components, fix TypeScript errors, and ensure responsiveness, follow the comprehensive steps below. We'll address each issue systematically:
TypeScript Errors:
Issue in EditProduct: TS71007: Props must be serializable for components in the "use client" entry file, "onClose" is invalid.
Issue in ProductsPage: Type mismatches between Product types, especially with price and qty fields.
UI/UX Enhancements:
Improve fonts, colors, and overall design.
Ensure responsiveness across devices.
Fix the bug where editing a product doesn't show sizes inside colors.
We'll start by addressing the TypeScript issues, then move on to UI/UX improvements.
1. Fixing TypeScript Errors
a. Unified Type Definitions
Ensure that both ProductsPage and EditProduct use the same type definitions. We'll update the types.ts to reflect the required structure accurately.
typescript Copy code
// src/components/types.ts
export interface Size {
id: number;
name: string;
price: number | null;
qty: number | null;
sold: number;
color_id: number | null;
images: string[];
}
export interface Color {
id: number;
name: string;
price: number | null;
qty: number | null;
sold: number;
has_size: boolean;
sizes: Size[];
images: string[];
}
export interface ImageType {
id: number;
url: string;
color_id: number | null;
size_id: number | null;
}
export interface Category {
id: number;
name: string;
main_category_id: number;
main_category_name: string;
}
export interface Product {
id: number;
name: string;
description: string;
brand_id: number;
has_color: boolean;
has_size: boolean;
product_type: "color" | "size" | "color_size" | "simple";
price: number | null;
qty: number | null;
sold: number;
created_at: string;
updated_at: string;
categories: Category[];
colors: Color[];
sizes: Size[];
images: ImageType[];
}
export interface ApiResponse {
products: Product[];
total: number;
page: number;
itemsPerPage: number;
totalPages: number;
hasMore: boolean;
}
export interface Brand {
id: number;
name: string;
}
b. Adjust EditProduct Component Types
Update the EditProduct component to use the unified types and ensure consistent handling of price and qty as numbers.
Key Changes:
Consistent Types: Ensured price and qty are handled as number | null across components.
Image Handling: Unified image structures to use arrays of strings representing URLs.
State Initialization: Properly initialized editedProduct with existing images.
Category Toggle: Fixed the category toggle to correctly add/remove categories.
Handle Submit: Aligned the payload structure with backend expectations, ensuring price and qty are numbers.
Responsive Design & Better UI: Updated class names with Tailwind CSS for better responsiveness and styling.
c. Fixing Props Serialization Error in EditProduct
The error TS71007: Props must be serializable for components in the "use client" entry file, "onClose" is invalid. occurs because Next.js expects props to be serializable (i.e., no functions) for Server Components. However, since EditProduct is a client component (as denoted by "use client";), this error shouldn't typically occur. To resolve this:
Ensure Proper Usage of Client Components:
Confirm that EditProduct is only used within client-side code.
Avoid nested Server Components within client components.
Alternative Approach using Portals:
Use React Portals to render modals, ensuring that parent components pass only serializable props.
Example using Portal:
typescript Copy code
// src/components/EditProduct.tsx
"use client";
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
// ... other imports
export default function EditProduct({ isOpen, onClose, product }: EditProductProps) {
if (!isOpen) return null;
return ReactDOM.createPortal(
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
{/* Modal Content */}
{/* ... existing content */}
</div>,
document.body
);
}
Note: Ensure that react-dom is available and that you're using appropriate methods to handle client-side rendering.
2. Enhancing UI/UX
a. Improving Fonts
Use a modern and clean font like Inter from Google Fonts for better readability and aesthetics.
Include Inter Font:
html Copy code
<!-- Add this to your _document.tsx or in the Head of your pages -->
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
Apply the Font Globally:
css Copy code
/* globals.css */
body {
font-family: 'Inter', sans-serif;
}
If you're using Tailwind CSS, configure it to use Inter:
javascript Copy code
// tailwind.config.js
module.exports = {
// ... other settings
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
},
},
// ... other settings
};
b. Enhancing Colors and Layouts
Use a consistent color palette that ensures good contrast and accessibility.
Utilize Tailwind CSS utility classes for responsive design.
Example Improvements in ProductsPage:
Key UI/UX Enhancements:
Font Improvement: Utilized Inter font for better readability.
Color Scheme: Applied consistent Tailwind CSS classes for colors, ensuring better contrast and accessibility.
Responsive Design: Leveraged Tailwind's responsive utilities (grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4) to ensure layouts adapt gracefully on different screen sizes.
Enhanced Buttons: Styled action buttons with hover effects for better interactivity.
Consistent Spacing and Sizing: Ensured uniform padding, margins, and font sizes across components for a cohesive look.
Improved Modals: Made modals centered with appropriate padding, rounded corners, and shadows for better focus.
c. Ensuring Responsiveness
Tailwind CSS makes it straightforward to create responsive designs. Here are some general tips:
Layout Adjustments:
Use responsive grid classes to adjust the number of columns based on screen size.
For forms and modals, use relative widths (w-full, max-w-3xl) to ensure they adapt to screen sizes.
Text and Element Sizing:
Use text-sm, text-base, text-lg, etc., to scale text appropriately.
Ensure buttons and input fields are touch-friendly on smaller devices.
Flexbox Utilities:
Use flex, flex-col, flex-row along with responsive variants like md:flex-row to adjust layouts.
Example Responsive Enhancements:
typescript Copy code
// Example Tailwind classes for responsiveness
<div className="flex flex-col md:flex-row">
<div className="w-full md:w-1/3">...</div>
<div className="w-full md:w-2/3">...</div>
</div>
3. Fixing the Bug: Sizes Not Displaying Inside Colors
From your description, when editing a product, sizes within colors aren't displaying correctly. This is likely due to how sizes are being handled in the EditProduct component.
a. Verify Backend Response
Ensure that the backend updateProduct function returns the updated product with correctly nested sizes within colors.
b. Update EditProduct to Handle Sizes Correctly
In the updated EditProduct component above, sizes within colors are mapped correctly. Ensure that:
Sizes Are Associated with the Correct Color:
Each size within a color should have color_id pointing to the parent color's ID.
Images for Sizes Are Captured:
Ensure that images uploaded for sizes are correctly linked via size_id.
c. Testing
After implementing the above changes, test the following:
Editing a Product with Colors and Sizes:
Open the edit modal for a product that has colors and sizes.
Verify that sizes within each color are displayed.
Make changes to sizes and ensure they persist after saving.
Responsive Behavior:
Test on various screen sizes to ensure the modal and forms are responsive.
Type Integrity:
Ensure that all fields (price, qty) are correctly typed and that no TypeScript errors appear during compilation.
4. Final Touches and Best Practices
a. Form Validation:
Implement client-side validation to ensure data integrity.
b. Optimizing Performance:
Memoization:
Use React.memo for components to prevent unnecessary re-renders.
Utilize useCallback and useMemo hooks appropriately, as shown in the ProductsPage component.
Lazy Loading Images:
Continue using the loading="lazy" attribute for images to improve load times.
c. Accessibility:
Ensure that all interactive elements are accessible:
ARIA Labels:
Add aria-labels where necessary, especially for icon buttons.
Keyboard Navigation:
Ensure that modals can be navigated via keyboard (e.g., focus trapping).
Contrast Ratios:
Verify that text has sufficient contrast against backgrounds.
d. Error Handling:
Provide user-friendly error messages.
Implement retry mechanisms for critical actions like fetching data or submitting forms.
e. Code Organization:
Component Structure:
Break down large components into smaller, reusable ones. For example, separate ColorForm, SizeForm, etc., from EditProduct.
State Management:
For more complex applications, consider using state management libraries like Redux or Zustand.
5. Example of a Refactored EditProduct Form Field for Colors and Sizes
To ensure that sizes within colors are displayed correctly, here's an example snippet focusing on rendering sizes within each color:
Key Points:
Nested Rendering: Sizes are rendered within their parent colors, ensuring a clear hierarchy.
Conditional Rendering: Sizes are only displayed if has_size is true for the color.
Consistent Styling: Utilized Tailwind CSS classes for uniformity.
6. Final Recommendations
Component Decomposition: Break down large components into smaller, reusable ones. For example, create separate ColorForm, SizeForm, and ImageUploader components to manage their respective functionalities.
State Management Libraries: For complex state interactions, consider using state management solutions like Zustand or Redux Toolkit .
Form Libraries: Implement form management and validation using libraries like React Hook Form or Formik with Yup for schema validation.
Accessibility Audits: Regularly perform accessibility audits using tools like Lighthouse to ensure your application is accessible to all users.
Performance Optimization: Utilize Next.js features like dynamic imports for code-splitting and better performance.
By implementing these changes, you'll resolve the TypeScript errors, fix the bug related to sizes within colors, and significantly enhance the overall user experience of your product editing and listing functionalities.
Show full message · 1,788 lines Copy first response
Not yet included in a published release.
// src/components/EditProduct.tsx
"use client";
import { X, Plus, Trash2 } from "lucide-react";
import { MultipartFileUploader } from "@/components/MultipartFileUploader";
import { toast } from "react-toastify";
import React, { useEffect, useState } from "react";
import { getToken } from "@/app/auth";
import { Product, Category, Brand, Size, Color } from "@/components/types";
interface EditProductProps {
isOpen: boolean;
onClose: () => void;
product: Product;
}
export default function EditProduct({
isOpen,
onClose,
product,
}: EditProductProps) {
const [editedProduct, setEditedProduct] = useState<Product>({
...product,
sizes: product.sizes || [],
colors: product.colors.map((color) => ({
...color,
sizes: color.sizes || [],
images: color.images || [],
})),
images: product.images.map((img) => img.url),
});
const [categories, setCategories] = useState<Category[]>([]);
const [brands, setBrands] = useState<Brand[]>([]);
useEffect(() => {
fetchCategories();
fetchBrands();
}, []);
const fetchCategories = async () => {
try {
const response = await fetch(
"http://localhost:4000/subcategories/non-brands",
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getToken()}`,
},
}
);
if (!response.ok) throw new Error("Failed to fetch categories");
const data = await response.json();
setCategories(data);
} catch (error) {
console.error("Error fetching categories:", error);
toast.error("Failed to fetch categories.");
}
};
const fetchBrands = async () => {
try {
const response = await fetch(
"http://localhost:4000/subcategories/brands",
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${getToken()}`,
},
}
);
if (!response.ok) throw new Error("Failed to fetch brands");
const data = await response.json();
setBrands(data);
} catch (error) {
console.error("Error fetching brands:", error);
toast.error("Failed to fetch brands.");
}
};
const handleDeleteColor = (colorIndex: number) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors.splice(colorIndex, 1);
return { ...prevProduct, colors: newColors };
});
};
const handleDeleteSize = (colorIndex: number, sizeIndex: number) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (colorIndex === -1) {
const newSizes = [...updatedProduct.sizes];
newSizes.splice(sizeIndex, 1);
return { ...updatedProduct, sizes: newSizes };
} else {
const newColors = [...updatedProduct.colors];
newColors[colorIndex].sizes.splice(sizeIndex, 1);
return { ...updatedProduct, colors: newColors };
}
});
};
const handleInheritImagesChange = (
variantType: "color" | "size",
colorIndex: number,
sizeIndex: number
) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (variantType === "color") {
updatedProduct.colors[colorIndex].has_size = !updatedProduct.colors[colorIndex].has_size;
// Optionally inherit images logic here
} else if (variantType === "size") {
// Size-specific logic
}
return updatedProduct;
});
};
const handleCategoryToggle = (categoryId: number) => {
setEditedProduct((prevProduct) => {
const isSelected = prevProduct.categories.some((cat) => cat.id === categoryId);
let updatedCategories: Category[] = [];
if (isSelected) {
updatedCategories = prevProduct.categories.filter((cat) => cat.id !== categoryId);
} else {
const category = categories.find((cat) => cat.id === categoryId);
if (category) updatedCategories = [...prevProduct.categories, category];
else updatedCategories = prevProduct.categories;
}
return { ...prevProduct, categories: updatedCategories };
});
};
const handleInputChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
const { name, value } = e.target;
setEditedProduct((prevProduct) => ({
...prevProduct,
[name]:
name === "price" || name === "qty" ? (value ? Number(value) : null) : value,
}));
};
const handleBrandChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setEditedProduct((prevProduct) => ({
...prevProduct,
brand_id: Number(e.target.value),
}));
};
const handleColorToggle = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
has_color: !prevProduct.has_color,
colors: !prevProduct.has_color ? [] : prevProduct.colors,
}));
};
const handleSizeToggle = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
has_size: !prevProduct.has_size,
sizes: !prevProduct.has_size ? [] : prevProduct.sizes,
}));
};
const handleAddColor = () => {
setEditedProduct((prevProduct) => ({
...prevProduct,
colors: [
...prevProduct.colors,
{ id: 0, name: "", price: null, qty: null, sold: 0, has_size: false, sizes: [], images: [] },
],
}));
};
const handleAddSize = (colorIndex: number) => {
setEditedProduct((prevProduct) => {
if (colorIndex === -1) {
return {
...prevProduct,
sizes: [
...prevProduct.sizes,
{ id: 0, name: "", price: null, qty: null, sold: 0, color_id: null, images: [] },
],
};
} else {
const newColors = [...prevProduct.colors];
newColors[colorIndex].sizes.push({
id: 0,
name: "",
price: null,
qty: null,
sold: 0,
color_id: newColors[colorIndex].id,
images: [],
});
return { ...prevProduct, colors: newColors };
}
});
};
const handleColorChange = (
index: number,
field: keyof Color,
value: string | boolean
) => {
setEditedProduct((prevProduct) => {
const newColors = [...prevProduct.colors];
newColors[index] = {
...newColors[index],
[field]: field === "has_size" ? Boolean(value) : (value as string | number | null),
};
return { ...prevProduct, colors: newColors };
});
};
const handleSizeChange = (
colorIndex: number,
sizeIndex: number,
field: keyof Size,
value: string | number | null
) => {
setEditedProduct((prevProduct) => {
const updatedProduct = { ...prevProduct };
if (colorIndex === -1) {
const newSizes = [...updatedProduct.sizes];
newSizes[sizeIndex] = {
...newSizes[sizeIndex],
[field]:
field === "price" || field === "qty"
? value === null
? null
: Number(value)
: value,
};
return { ...updatedProduct, sizes: newSizes };
} else {
const newColors = [...updatedProduct.colors];
newColors[colorIndex].sizes[sizeIndex] = {
...newColors[colorIndex].sizes[sizeIndex],
[field]:
field === "price" || field === "qty"
? value === null
? null
: Number(value)
: value,
};
return { ...updatedProduct, colors: newColors };
}
});
};
const handleImageUpload = (
fileIds: string[],
variantType: "color" | "size" | "product",
colorIndex: number,
sizeIndex: number
) => {
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: React.FormEvent) => {
e.preventDefault();
const productType =
editedProduct.has_color && editedProduct.has_size
? "color_size"
: editedProduct.has_color
? "color"
: editedProduct.has_size
? "size"
: "simple";
const productData = {
name: editedProduct.name,
description: editedProduct.description,
brand_id: editedProduct.brand_id,
has_color: editedProduct.has_color,
has_size: editedProduct.has_size,
product_type: productType,
price: editedProduct.price,
qty: editedProduct.qty,
category_ids: editedProduct.categories.map((cat) => cat.id),
images: editedProduct.images.map((url) => ({ url, color_id: null, size_id: null })),
colors: editedProduct.colors.map((color) => ({
id: color.id === 0 ? undefined : color.id,
name: color.name,
price: color.price,
qty: color.qty,
has_size: color.has_size,
images: color.images.map((url) => ({ url, color_id: color.id, size_id: null })),
sizes: color.has_size
? color.sizes.map((size) => ({
id: size.id === 0 ? undefined : size.id,
name: size.name,
price: size.price,
qty: size.qty,
images: size.images.map((url) => ({ url, color_id: color.id, size_id: size.id })),
}))
: [],
})),
sizes: editedProduct.has_size && !editedProduct.has_color
? editedProduct.sizes.map((size) => ({
id: size.id === 0 ? undefined : size.id,
name: size.name,
price: size.price,
qty: size.qty,
images: size.images.map((url) => ({ url, color_id: null, size_id: size.id })),
}))
: [],
};
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: Product = await response.json();
toast.success("Product updated successfully!");
onClose();
// Optionally, you can emit an event or use a context to update the product list in ProductsPage
} 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 px-4">
<div className="relative w-full max-w-3xl rounded-lg bg-white p-8 overflow-y-auto max-h-full">
<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 text-gray-800">Edit Product</h2>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Product Name */}
<div>
<label htmlFor="name" className="block text-sm font-semibold text-gray-700">
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 htmlFor="description" className="block text-sm font-semibold text-gray-700">
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}
required
/>
</div>
{/* Categories */}
<div>
<span className="block text-sm font-semibold text-gray-700">Categories</span>
<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-600 text-white"
: "bg-gray-200 text-gray-700 hover:bg-gray-300"
} transition-colors`}
>
{category.name}
</button>
))}
</div>
</div>
{/* Brand */}
<div>
<label htmlFor="brand_id" className="block text-sm font-semibold text-gray-700">
Brand
</label>
<select
id="brand_id"
name="brand_id"
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={handleColorToggle}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_color" className="ml-2 block text-sm font-medium text-gray-700">
Has Color?
</label>
</div>
{/* Colors */}
{editedProduct.has_color && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold text-gray-700">Colors</span>
<button
type="button"
onClick={handleAddColor}
className="flex items-center rounded bg-green-500 px-3 py-2 text-white hover:bg-green-600"
>
<Plus size={16} className="mr-1" />
Add Color
</button>
</div>
{editedProduct.colors.map((color, colorIndex) => (
<div key={colorIndex} className="space-y-2 rounded border p-4">
<div className="flex items-center justify-between">
<input
type="text"
value={color.name}
onChange={(e) => handleColorChange(colorIndex, "name", e.target.value)}
placeholder="Color Name"
className="w-full rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<button
type="button"
onClick={() => handleDeleteColor(colorIndex)}
className="ml-4 text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<input
type="number"
value={color.price ?? ""}
onChange={(e) => handleColorChange(colorIndex, "price", e.target.value ? Number(e.target.value) : null)}
placeholder="Price"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required={!color.has_size}
/>
<input
type="number"
value={color.qty ?? ""}
onChange={(e) => handleColorChange(colorIndex, "qty", e.target.value ? Number(e.target.value) : null)}
placeholder="Quantity"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required={!color.has_size}
/>
</div>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "color", colorIndex, -1)
}
existingImages={color.images}
/>
{/* Sizes within Color */}
{color.has_size && (
<div className="mt-4">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold text-gray-700">Sizes</span>
<button
type="button"
onClick={() => handleAddSize(colorIndex)}
className="flex items-center rounded bg-green-500 px-3 py-2 text-white hover:bg-green-600"
>
<Plus size={16} className="mr-1" />
Add Size
</button>
</div>
{color.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="mt-2 space-y-2 rounded border p-2">
<div className="flex items-center justify-between">
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(colorIndex, sizeIndex, "name", e.target.value)
}
placeholder="Size Name"
className="w-full rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<button
type="button"
onClick={() => handleDeleteSize(colorIndex, sizeIndex)}
className="ml-4 text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<input
type="number"
value={size.price ?? ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"price",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Price"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<input
type="number"
value={size.qty ?? ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"qty",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Quantity"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", colorIndex, sizeIndex)
}
existingImages={size.images}
/>
</div>
))}
</div>
)}
</div>
))}
</div>
)}
{/* Has Size (Global) */}
<div className="flex items-center">
<input
type="checkbox"
id="has_size"
checked={editedProduct.has_size}
onChange={handleSizeToggle}
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<label htmlFor="has_size" className="ml-2 block text-sm font-medium text-gray-700">
Has Size?
</label>
</div>
{/* Sizes (Global) */}
{editedProduct.has_size && !editedProduct.has_color && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold text-gray-700">Sizes</span>
<button
type="button"
onClick={() => handleAddSize(-1)}
className="flex items-center rounded bg-green-500 px-3 py-2 text-white hover:bg-green-600"
>
<Plus size={16} className="mr-1" />
Add Size
</button>
</div>
{editedProduct.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="space-y-2 rounded border p-4">
<div className="flex items-center justify-between">
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(-1, sizeIndex, "name", e.target.value)
}
placeholder="Size Name"
className="w-full rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<button
type="button"
onClick={() => handleDeleteSize(-1, sizeIndex)}
className="ml-4 text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<input
type="number"
value={size.price ?? ""}
onChange={(e) =>
handleSizeChange(
-1,
sizeIndex,
"price",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Price"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<input
type="number"
value={size.qty ?? ""}
onChange={(e) =>
handleSizeChange(
-1,
sizeIndex,
"qty",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Quantity"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", -1, sizeIndex)
}
existingImages={size.images}
/>
</div>
))}
</div>
)}
{/* Product Images */}
{!editedProduct.has_color && !editedProduct.has_size && (
<div>
<span className="block text-sm font-semibold text-gray-700">Images</span>
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "product", -1, -1)
}
existingImages={editedProduct.images}
/>
</div>
)}
{/* Submit Button */}
<div className="flex justify-end">
<button
type="submit"
className="rounded bg-blue-600 px-6 py-2 text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Save Changes
</button>
</div>
</form>
</div>
</div>
);
}
// src/pages/products.tsx
"use client";
import React, { /* ... */ } from "react";
import Head from "next/head";
import Image from "next/image";
import {
Search,
Grid,
List,
Plus,
Edit,
Trash2,
} 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";
import { Product, Brand, ApiResponse, Category } from "@/components/types";
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString(); // 'MM/DD/YYYY' format
};
const PRODUCTS_PER_PAGE = 15;
const ProductsPage: React.FC = () => {
// State Variables
const [products, setProducts] = useState<Product[]>([]);
const [brands, setBrands] = useState<Brand[]>([]);
const [brandMap, setBrandMap] = useState<{ [key: number]: string }>({});
const [currentPage, setCurrentPage] = useState<number>(1);
const [searchTerm, setSearchTerm] = useState<string>("");
const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
const [sortBy, setSortBy] = useState<keyof Product>("created_at");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [isAddProductDialogOpen, setIsAddProductDialogOpen] = useState<boolean>(false);
const [isEditProductDialogOpen, setIsEditProductDialogOpen] = useState<boolean>(false);
const [productToEdit, setProductToEdit] = useState<Product | null>(null);
const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState<boolean>(false);
const [productToDelete, setProductToDelete] = useState<Product | null>(null);
const [isDeleting, setIsDeleting] = useState<boolean>(false);
const [totalPages, setTotalPages] = useState<number>(1);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [searchInput, setSearchInput] = useState<string>("");
// Debounce the search input to prevent excessive API calls
const debouncedSearch = React.useMemo(
() =>
debounce((term: string) => {
setSearchTerm(term);
setCurrentPage(1);
}, 300),
[]
);
useEffect(() => {
debouncedSearch(searchInput);
return () => {
debouncedSearch.cancel();
};
}, [searchInput, debouncedSearch]);
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchInput(e.target.value);
};
// Fetch Brand Details
const fetchBrands = React.useCallback(async () => {
const token = getToken();
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: Brand[] = await response.json();
setBrands(data);
const map: { [key: number]: string } = {};
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 = React.useCallback(async () => {
setIsLoading(true);
const token = getToken();
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: ApiResponse = 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 = React.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 = React.useCallback((product: Product) => {
setProductToEdit(product);
setIsEditProductDialogOpen(true);
}, []);
const handleDeleteClick = React.useCallback((product: Product) => {
setProductToDelete(product);
setIsDeleteConfirmOpen(true);
}, []);
const handleDeleteConfirm = React.useCallback(async () => {
if (productToDelete) {
setIsDeleting(true);
const token = getToken();
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]);
// Handle Pagination
const handlePageChange = React.useCallback((newPage: number) => {
setCurrentPage(newPage);
window.scrollTo({ top: 0, behavior: "smooth" });
}, []);
return (
<div className="font-sans min-h-screen bg-gray-100">
<Head>
<title>Products - Naay Store</title>
<link rel="icon" href="/favicon.ico" />
{/* Inter Font */}
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;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 & 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 as keyof Product)}
>
<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 as "asc" | "desc")}
>
<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 primaryImage = product.images[0]?.url || "";
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%]`}
>
{primaryImage ? (
<Image
src={`https://storage.naayiq.com/resources/${primaryImage}`}
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>{" "}
{product.has_color
? product.colors[0]?.price !== null
? `$${product.colors[0]?.price.toLocaleString()}`
: `$${product.price?.toLocaleString() || "N/A"}`
: `$${product.price?.toLocaleString() || "N/A"}`}
</p>
{/* Display Quantity */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Quantity:</span>{" "}
{product.has_color
? product.colors[0]?.qty !== null
? product.colors[0]?.qty
: product.qty
: product.qty || "N/A"}
</p>
{/* Display Sold */}
<p className="text-sm text-gray-600">
<span className="font-semibold">Sold:</span>{" "}
{product.has_color
? product.colors[0]?.sold
: product.sold}
</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 Sizes within Colors */}
{product.has_color && product.colors[0]?.has_size && (
<div className="mt-2">
{product.colors[0].sizes.map((size) => (
<div key={size.id} className="flex space-x-2 text-sm text-gray-600">
<span className="font-semibold">Size:</span>
<span>{size.name}</span>
<span className="font-semibold">Price:</span>
<span>${size.price?.toLocaleString() || "N/A"}</span>
<span className="font-semibold">Qty:</span>
<span>{size.qty || "N/A"}</span>
</div>
))}
</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: Product) => {
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}
/>
)}
{/* 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);
{/* Colors */}
{editedProduct.has_color && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold text-gray-700">Colors</span>
<button
type="button"
onClick={handleAddColor}
className="flex items-center rounded bg-green-500 px-3 py-2 text-white hover:bg-green-600"
>
<Plus size={16} className="mr-1" />
Add Color
</button>
</div>
{editedProduct.colors.map((color, colorIndex) => (
<div key={colorIndex} className="space-y-2 rounded border p-4">
{/* Color Details */}
<div className="flex items-center justify-between">
<input
type="text"
value={color.name}
onChange={(e) => handleColorChange(colorIndex, "name", e.target.value)}
placeholder="Color Name"
className="w-full rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<button
type="button"
onClick={() => handleDeleteColor(colorIndex)}
className="ml-4 text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
{/* Color Price and Quantity */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<input
type="number"
value={color.price ?? ""}
onChange={(e) =>
handleColorChange(colorIndex, "price", e.target.value ? Number(e.target.value) : null)
}
placeholder="Price"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required={!color.has_size}
/>
<input
type="number"
value={color.qty ?? ""}
onChange={(e) =>
handleColorChange(colorIndex, "qty", e.target.value ? Number(e.target.value) : null)
}
placeholder="Quantity"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required={!color.has_size}
/>
</div>
{/* Color Images */}
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "color", colorIndex, -1)
}
existingImages={color.images}
/>
{/* Sizes within Color */}
{color.has_size && (
<div className="mt-4">
<div className="flex items-center justify-between">
<span className="text-sm font-semibold text-gray-700">Sizes</span>
<button
type="button"
onClick={() => handleAddSize(colorIndex)}
className="flex items-center rounded bg-green-500 px-3 py-2 text-white hover:bg-green-600"
>
<Plus size={16} className="mr-1" />
Add Size
</button>
</div>
{color.sizes.map((size, sizeIndex) => (
<div key={sizeIndex} className="mt-2 space-y-2 rounded border p-2">
<div className="flex items-center justify-between">
<input
type="text"
value={size.name}
onChange={(e) =>
handleSizeChange(colorIndex, sizeIndex, "name", e.target.value)
}
placeholder="Size Name"
className="w-full rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<button
type="button"
onClick={() => handleDeleteSize(colorIndex, sizeIndex)}
className="ml-4 text-red-500 hover:text-red-700"
>
<Trash2 size={20} />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<input
type="number"
value={size.price ?? ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"price",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Price"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
<input
type="number"
value={size.qty ?? ""}
onChange={(e) =>
handleSizeChange(
colorIndex,
sizeIndex,
"qty",
e.target.value ? Number(e.target.value) : null
)
}
placeholder="Quantity"
className="rounded-md border-gray-300 p-2 shadow-sm focus:border-blue-500 focus:ring-blue-500"
required
/>
</div>
{/* Size Images */}
<MultipartFileUploader
onUploadSuccess={(fileIds) =>
handleImageUpload(fileIds, "size", colorIndex, sizeIndex)
}
existingImages={size.images}
/>
</div>
))}
</div>
)}
</div>
))}
</div>
)}