Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 3x 3x 4x 2x 2x 2x 2x 3x 3x 3x 130x 130x 130x 130x 130x 37x 37x 37x 37x 37x 37x 37x 37x 37x 36x 37x 1x 1x 35x 35x 35x 35x 35x 35x 35x 37x 2x 2x 2x 2x 37x 37x 37x 130x 130x 130x 37x 130x 130x 130x 130x 37x 37x 37x 37x 37x 37x 130x 130x 130x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 130x 130x 130x 1x 1x 130x 130x 130x 130x 130x 130x 2x 130x 130x 130x 130x 130x 130x 130x 130x 130x 1x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 5x 5x 5x 5x 5x 5x 5x 5x 5x 130x 130x 130x 130x 130x 2x 2x 2x 130x 130x 130x 74x 74x 74x 130x 4x 4x 4x 1x 1x 1x 4x 4x 56x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 154x 154x 154x 154x 154x 154x 102x 102x 102x 102x 102x 102x 102x 102x 102x 154x 52x 52x 52x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 154x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x 130x | "use client";
import { useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import Image from "next/image";
import { clientLogger } from "@/lib/logging/clientLogger";
import { PriceDisplay, Button, Input } from "@/components/ui";
import { Icon } from "@/components/ui/icons";
import { useDeleteConfirm } from "@/hooks/useConfirm";
import { AdminPagination } from "@/components/features/admin/AdminPagination";
import { ProductModal } from "@/components/features/admin/ProductModal";
interface ProductImage {
id: number;
url: string;
thumbnailUrl: string;
order: number;
}
interface Product {
id: number;
title: string;
sku: string;
price: number;
discountedPrice: number;
stock: number;
category: { title: string };
categoryId: number;
description: string;
images: ProductImage[];
rating?: number;
reviewCount?: number;
}
interface PaginationData {
page: number;
limit: number;
total: number;
pages: number;
}
export const ProductList: React.FC = () => {
const router = useRouter();
const searchParams = useSearchParams();
const { confirmDelete, ConfirmDialog } = useDeleteConfirm();
// Read state from URL
const urlPage = Number(searchParams.get("page")) || 1;
const urlPageSize = Number(searchParams.get("pageSize")) || 20;
const urlSearch = searchParams.get("search") || "";
const [products, setProducts] = useState<Product[]>([]);
const [pagination, setPagination] = useState<PaginationData>({
page: urlPage,
limit: urlPageSize,
total: 0,
pages: 0,
});
const [loading, setLoading] = useState(true);
const [searchInput, setSearchInput] = useState(urlSearch);
const [error, setError] = useState("");
// Modal state
const [editingProductId, setEditingProductId] = useState<number | null>(null);
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
// Update URL params
const updateUrlParams = useCallback(
(updates: Record<string, string | number | null>) => {
const params = new URLSearchParams(searchParams.toString());
Object.entries(updates).forEach(([key, value]) => {
if (value === null || value === "" || value === 1) {
params.delete(key);
} else {
params.set(key, String(value));
}
});
const newUrl = params.toString() ? `?${params.toString()}` : "";
router.push(`/admin/products${newUrl}`, { scroll: false });
},
[router, searchParams]
);
const fetchProducts = useCallback(async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
params.set("page", String(pagination.page));
params.set("limit", String(pagination.limit));
if (urlSearch) params.set("search", urlSearch);
const response = await fetch(`/api/admin/products?${params}`);
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const result = await response.json();
if (result.success) {
setProducts(result.data);
setPagination(result.pagination);
}
} catch (err) {
const error =
err instanceof Error ? err : new Error("Failed to fetch products");
setError(error.message);
clientLogger.error("Failed to fetch products", error);
} finally {
setLoading(false);
}
}, [pagination.page, pagination.limit, urlSearch]);
useEffect(() => {
fetchProducts();
}, [fetchProducts]);
// Sync URL params to state
useEffect(() => {
setPagination((prev) => ({
...prev,
page: urlPage,
limit: urlPageSize,
}));
setSearchInput(urlSearch);
}, [urlPage, urlPageSize, urlSearch]);
const handleDelete = async (productId: number, productTitle: string) => {
const confirmed = await confirmDelete(productTitle);
if (!confirmed) {
return;
}
try {
const response = await fetch(`/api/admin/products/${productId}`, {
method: "DELETE",
});
if (response.ok) {
setProducts((prev) => prev.filter((p) => p.id !== productId));
setPagination((prev) => ({ ...prev, total: prev.total - 1 }));
} else {
alert("Failed to delete product");
}
} catch (err) {
clientLogger.error("Failed to delete product", err instanceof Error ? err : new Error(String(err)));
alert("Failed to delete product");
}
};
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
updateUrlParams({ search: searchInput, page: null });
};
const clearSearch = () => {
setSearchInput("");
updateUrlParams({ search: null, page: null });
};
const handlePageChange = (newPage: number) => {
updateUrlParams({ page: newPage === 1 ? null : newPage });
};
const handlePageSizeChange = (newSize: number) => {
updateUrlParams({ pageSize: newSize === 20 ? null : newSize, page: null });
};
const handleEdit = (productId: number) => {
setEditingProductId(productId);
};
const handleAdd = () => {
setIsAddModalOpen(true);
};
const handleProductSaved = (product: Product) => {
setProducts((prev) =>
prev.map((p) => (p.id === product.id ? product : p))
);
setEditingProductId(null);
};
const handleProductCreated = () => {
// Refresh the list to show the new product
fetchProducts();
setIsAddModalOpen(false);
};
return (
<div className="p-8 md:p-4 max-w-[1400px] mx-auto">
<div className="flex justify-between items-center mb-8 flex-wrap gap-5 md:flex-col md:items-start">
<div>
<h1 className="m-0 text-3xl text-gray-800 dark:text-gray-100">
Products
</h1>
<p className="mt-1 mb-0 text-gray-500 dark:text-gray-400 text-sm">
Manage your product catalog ({pagination.total} total)
</p>
</div>
<Button
onClick={handleAdd}
variant="primary"
className="md:self-end"
>
<Icon name="plus" size={18} className="mr-2" />
Add Product
</Button>
</div>
{/* Search Bar - Fixed Layout */}
<div className="mb-6">
<form onSubmit={handleSearch} className="flex gap-2.5 items-center">
<div className="flex-1 flex gap-2">
<Input
type="text"
placeholder="Search by title or SKU..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="flex-1 min-w-0"
/>
<Button type="submit" variant="primary" size="sm" className="shrink-0">
<Icon name="search" size={16} />
<span className="hidden sm:inline ml-2">Search</span>
</Button>
</div>
{urlSearch && (
<Button
type="button"
variant="secondary"
size="sm"
onClick={clearSearch}
className="shrink-0"
>
Clear
</Button>
)}
</form>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-900/30 text-red-800 dark:text-red-300 border border-red-200 dark:border-red-800 rounded py-3 px-4 mb-5 text-sm">
{error}
</div>
)}
{loading ? (
<div className="text-center py-16 px-5 text-gray-500 dark:text-gray-400 text-base">
Loading products...
</div>
) : products.length === 0 ? (
<div className="text-center py-20 px-5 text-gray-400 dark:text-gray-500">
<p className="my-2.5 text-base">No products found</p>
{urlSearch && (
<p className="text-sm text-gray-400 dark:text-gray-500">
Try a different search term
</p>
)}
</div>
) : (
<>
<div className="bg-white dark:bg-gray-800 rounded-lg overflow-hidden shadow-sm mb-6 overflow-x-auto">
<table className="w-full border-collapse text-sm lg:text-[13px]">
<thead className="bg-gray-50 dark:bg-gray-700 border-b-2 border-gray-200 dark:border-gray-600">
<tr>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Image
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Title
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
SKU
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Category
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Price
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Stock
</th>
<th className="p-4 lg:p-2.5 text-left font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Images
</th>
<th className="p-4 lg:p-2.5 text-center font-semibold text-gray-800 dark:text-gray-200 whitespace-nowrap">
Actions
</th>
</tr>
</thead>
<tbody>
{products.map((product) => (
<tr
key={product.id}
className="hover:bg-gray-50 dark:hover:bg-gray-700"
>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 w-20">
{product.images && product.images.length > 0 ? (
<Image
src={
product.images[0].thumbnailUrl ||
product.images[0].url
}
alt={product.title}
width={50}
height={50}
className="w-[60px] md:w-10 h-[60px] md:h-10 object-cover rounded"
/>
) : (
<div className="w-[60px] md:w-10 h-[60px] md:h-10 bg-gray-100 dark:bg-gray-700 rounded flex items-center justify-center text-[11px] text-gray-400 dark:text-gray-500 text-center p-1">
No image
</div>
)}
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 max-w-[250px] lg:max-w-[150px]">
<div className="font-medium text-gray-800 dark:text-gray-200 overflow-hidden text-ellipsis whitespace-nowrap">
{product.title}
</div>
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400 font-mono text-xs">
{product.sku || "—"}
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400">
{product.category?.title || "—"}
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 font-semibold">
<PriceDisplay
price={product.price}
discountedPrice={product.discountedPrice}
size="sm"
/>
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 text-center">
<span
className={`py-1 px-2 rounded text-xs font-semibold ${
product.stock > 0
? "bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300"
: "bg-red-50 dark:bg-red-900/30 text-red-800 dark:text-red-300"
}`}
>
{product.stock}
</span>
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700 text-center text-gray-500 dark:text-gray-400">
{product.images.length}
</td>
<td className="p-4 lg:p-2.5 border-b border-gray-200 dark:border-gray-700">
<div className="flex gap-1 justify-center">
<button
onClick={() => handleEdit(product.id)}
className="p-2 rounded hover:bg-blue-100 dark:hover:bg-blue-900/30 text-blue-600 dark:text-blue-400 transition-colors"
title="Edit product"
aria-label={`Edit ${product.title}`}
>
<Icon name="edit" size={18} />
</button>
<button
onClick={() => handleDelete(product.id, product.title)}
className="p-2 rounded hover:bg-red-100 dark:hover:bg-red-900/30 text-red-600 dark:text-red-400 transition-colors"
title="Delete product"
aria-label={`Delete ${product.title}`}
>
<Icon name="trash" size={18} />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination */}
<AdminPagination
page={pagination.page}
pageSize={pagination.limit}
total={pagination.total}
onPageChange={handlePageChange}
onPageSizeChange={handlePageSizeChange}
pageSizeOptions={[10, 20, 50, 100]}
className="py-4"
/>
</>
)}
<ConfirmDialog />
{/* Edit Modal */}
<ProductModal
isOpen={editingProductId !== null}
onClose={() => setEditingProductId(null)}
productId={editingProductId}
onSave={handleProductSaved}
/>
{/* Add Modal */}
<ProductModal
isOpen={isAddModalOpen}
onClose={() => setIsAddModalOpen(false)}
onSave={handleProductSaved}
onProductCreated={handleProductCreated}
/>
</div>
);
};
|