"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { authFetch, clearToken, getApiBase, getToken } from "../../lib/auth"; import AdminShell from "../../ui/AdminShell"; type RequestRow = { id: number; title?: string | null; year?: number | null; type?: string | null; statusLabel?: string | null; requestedBy?: string | null; createdAt?: string | null; }; const REQUEST_STAGE_OPTIONS = [ { value: "all", label: "All stages" }, { value: "pending", label: "Waiting for approval" }, { value: "approved", label: "Approved" }, { value: "in_progress", label: "In progress" }, { value: "working", label: "Working on it" }, { value: "partial", label: "Partially ready" }, { value: "ready", label: "Ready to watch" }, { value: "declined", label: "Declined" }, ]; const formatDateTime = (value?: string | null) => { if (!value) return "Unknown"; const date = new Date(value); if (Number.isNaN(date.valueOf())) return value; return date.toLocaleString(); }; export default function AdminRequestsAllPage() { const router = useRouter(); const [rows, setRows] = useState([]); const [total, setTotal] = useState(0); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [pageSize, setPageSize] = useState(50); const [page, setPage] = useState(1); const [stage, setStage] = useState("all"); const pageCount = useMemo(() => { if (!total || pageSize <= 0) return 1; return Math.max(1, Math.ceil(total / pageSize)); }, [total, pageSize]); const load = useCallback(async () => { if (!getToken()) { router.push("/login"); return; } setLoading(true); setError(null); try { const baseUrl = getApiBase(); const skip = (page - 1) * pageSize; const params = new URLSearchParams({ take: String(pageSize), skip: String(skip), }); if (stage !== "all") { params.set("stage", stage); } const response = await authFetch(`${baseUrl}/admin/requests/all?${params.toString()}`); if (!response.ok) { if (response.status === 401) { clearToken(); router.push("/login"); return; } if (response.status === 403) { router.push("/"); return; } throw new Error(`Load failed: ${response.status}`); } const data = await response.json(); setRows(Array.isArray(data?.results) ? data.results : []); setTotal(Number(data?.total ?? 0)); } catch (err) { console.error(err); setError("Unable to load requests."); } finally { setLoading(false); } }, [page, pageSize, router, stage]); useEffect(() => { void load(); }, [load]); useEffect(() => { if (page > pageCount) { setPage(pageCount); } }, [pageCount, page]); useEffect(() => { void stage; setPage(1); }, [stage]); return (
{total.toLocaleString()} total
{loading ? (
Loading requests…
) : error ? (
{error}
) : rows.length === 0 ? (
No requests found.
) : (
Request Status Requested by Created
{rows.map((row) => ( ))}
)}
Page {page} of {pageCount}
); }