/** * Admin dashboard (M6): paginated list of all items with debounced * search (300ms), sortable columns (title / points / created date), * page-size selector, row actions (edit / delete) and a success notice * after saves coming back from the edit page. */ import { ArrowDown, ArrowUp, ArrowUpDown, Pencil, Plus, RefreshCw, Search, Trash2, } from 'lucide-react'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { Link, useLocation } from 'react-router-dom'; import { adminDeleteItem, adminListItems } from '../api/admin'; import { DeleteConfirmation } from '../components/DeleteConfirmation'; import { ApiError } from '../api/client'; import { cn } from '../lib/utils'; import type { AdminItem, AdminItemsPage, AdminSortBy, AdminSortOrder, } from '../types/admin'; const PAGE_SIZES = [10, 20, 50]; const SEARCH_DEBOUNCE_MS = 300; interface AdminDashboardState { page: number; pageSize: number; search: string; sortBy: AdminSortBy; sortOrder: AdminSortOrder; } const INITIAL_STATE: AdminDashboardState = { page: 1, pageSize: 20, search: '', sortBy: 'created_at', sortOrder: 'desc', }; /** "2024-05-01T12:30:00Z" -> "01 May 2024, 12:30" (empty on bad input). */ function formatDateTime(value: string): string { const date = new Date(value); if (Number.isNaN(date.getTime())) return value; return date.toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', }); } /** Compact page-number window with ellipses, e.g. [1, '…', 4, 5, 6, '…', 12]. */ function pageWindow(current: number, total: number): (number | '…')[] { if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1); const pages = new Set([1, 2, total - 1, total, current - 1, current, current + 1]); const sorted = [...pages].filter((p) => p >= 1 && p <= total).sort((a, b) => a - b); const out: (number | '…')[] = []; let previous = 0; for (const p of sorted) { if (p - previous > 1) out.push('…'); out.push(p); previous = p; } return out; } export function AdminDashboard() { const [state, setState] = useState(INITIAL_STATE); const [debouncedSearch, setDebouncedSearch] = useState(''); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [pendingDelete, setPendingDelete] = useState(null); const [deleteBusy, setDeleteBusy] = useState(false); const [deleteError, setDeleteError] = useState(null); const [notice, setNotice] = useState(null); const location = useLocation(); // Success notice passed by the edit page after a save. useEffect(() => { const passed = (location.state as { notice?: string } | null)?.notice; if (passed) { setNotice(passed); // Clear it from router state so a refresh does not re-show it. window.history.replaceState({}, ''); } }, [location.state]); // Debounce the search input (300ms) before it reaches the API. useEffect(() => { const timer = setTimeout(() => setDebouncedSearch(state.search), SEARCH_DEBOUNCE_MS); return () => clearTimeout(timer); }, [state.search]); const searchActive = debouncedSearch.trim(); const load = useCallback( async (signal?: { cancelled: boolean }) => { setLoading(true); setError(null); try { const result = await adminListItems({ page: state.page, pageSize: state.pageSize, search: searchActive, sortBy: state.sortBy, sortOrder: state.sortOrder, }); if (signal?.cancelled) return; setData(result); } catch (err) { if (signal?.cancelled) return; setError( err instanceof ApiError ? err.message : 'Something went wrong while loading items.', ); } finally { if (!signal?.cancelled) setLoading(false); } }, [state, searchActive], ); useEffect(() => { const signal = { cancelled: false }; void load(signal); return () => { signal.cancelled = true; }; }, [load]); const update = (patch: Partial) => setState((current) => ({ ...current, ...patch })); // Search resets to page 1 (the debounced value drives the fetch). const onSearchChange = (value: string) => update({ search: value, page: 1 }); const onSort = (field: AdminSortBy) => setState((current) => current.sortBy === field ? { ...current, sortOrder: current.sortOrder === 'asc' ? 'desc' : 'asc', page: 1, } : { ...current, sortBy: field, sortOrder: 'asc', page: 1 }, ); const onPageSizeChange = (size: number) => update({ pageSize: size, page: 1 }); const onPageChange = (page: number) => update({ page }); const confirmDelete = async () => { if (!pendingDelete) return; setDeleteBusy(true); setDeleteError(null); try { await adminDeleteItem(pendingDelete.id); setPendingDelete(null); setNotice(`“${pendingDelete.title}” was deleted.`); await load(); } catch (err) { setDeleteError(err instanceof ApiError ? err.message : 'Deleting the item failed.'); } finally { setDeleteBusy(false); } }; const cancelDelete = () => { setPendingDelete(null); setDeleteError(null); }; const range = useMemo(() => { if (!data || data.total === 0) return null; const start = (data.page - 1) * data.page_size + 1; const end = Math.min(data.page * data.page_size, data.total); return { start, end, total: data.total }; }, [data]); const totalPages = data?.total_pages ?? 0; const sortIndicator = (field: AdminSortBy) => state.sortBy !== field ? (