"use client"; import { AlertCircle, Check, Download, Loader2, Package, PawPrint, Search, Trash2, X, } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { adminFetch } from "@/lib/admin-fetch"; import { runSseImport } from "@/lib/sse-client"; import { cn } from "@/lib/utils"; interface PetItem { lib: string; nitroExists: boolean; } /** Real pet preview cropped from its .nitro; falls back to the paw glyph. */ function PetIcon({ lib }: { lib: string }) { const [failed, setFailed] = useState(false); if (failed) return ; return ( {lib} setFailed(true)} /> ); } export function ImportPetsClient() { const [searchTerm, setSearchTerm] = useState(""); const [pets, setPets] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [selected, setSelected] = useState>(new Set()); const [batchProgress, setBatchProgress] = useState<{ done: number; total: number; } | null>(null); const [busyLib, setBusyLib] = useState(null); const batchAbortRef = useRef(null); const fetchPets = useCallback(async (search: string) => { setLoading(true); setError(""); try { const params = new URLSearchParams(); if (search) params.set("search", search); const res = await adminFetch(`/api/admin/import/pets?${params}`); const data = await res.json(); if (!res.ok) { setError(data.error || "Failed to load"); return; } setPets(data.pets || []); setSelected(new Set()); } catch { setError("Network error"); } finally { setLoading(false); } }, []); useEffect(() => { fetchPets(""); }, [fetchPets]); const importable = useMemo(() => pets.filter((p) => !p.nitroExists), [pets]); const importedCount = useMemo( () => pets.filter((p) => p.nitroExists).length, [pets], ); function toggle(lib: string) { setSelected((prev) => { const n = new Set(prev); if (n.has(lib)) n.delete(lib); else n.add(lib); return n; }); } function markDone(lib: string) { setPets((prev) => prev.map((p) => (p.lib === lib ? { ...p, nitroExists: true } : p)), ); } async function importViaSse(items: PetItem[]) { batchAbortRef.current?.abort(); const abort = new AbortController(); batchAbortRef.current = abort; setBatchProgress({ done: 0, total: items.length }); let done = 0; try { await runSseImport( "/api/admin/import/pets/batch", { items, concurrency: 3 }, (lib) => { done++; markDone(lib); setBatchProgress({ done, total: items.length }); }, (succeeded, failed) => { setSelected(new Set()); if (succeeded > 0) toast.success(`${succeeded} pet(s) imported`); if (failed > 0) toast.error(`${failed} failed`); }, abort.signal, () => { done++; setBatchProgress({ done, total: items.length }); }, ); } catch (err) { if ((err as Error)?.name === "AbortError") { toast.info("Import cancelled"); } else { throw err; } } finally { if (batchAbortRef.current === abort) batchAbortRef.current = null; setBatchProgress(null); } } async function importOne(p: PetItem) { setBusyLib(p.lib); try { await importViaSse([p]); } finally { setBusyLib(null); } } async function importSelected() { const items = pets.filter((p) => selected.has(p.lib) && !p.nitroExists); if (items.length === 0) return; await importViaSse(items); } async function remove(p: PetItem) { setBusyLib(p.lib); try { const res = await adminFetch( `/api/admin/import/pets?lib=${encodeURIComponent(p.lib)}`, { method: "DELETE", }, ); const data = await res.json(); if (res.ok) { toast.success(`${p.lib} removed`); setPets((prev) => prev.map((x) => (x.lib === p.lib ? { ...x, nitroExists: false } : x)), ); } else { toast.error(data.error || "Delete failed"); } } finally { setBusyLib(null); } } return (
{pets.length > 0 && (
{pets.length} pets
{importedCount} imported
{importable.length} missing
)}
setSearchTerm(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") fetchPets(searchTerm); if (e.key === "Escape") { setSearchTerm(""); fetchPets(""); } }} className="pl-9 pr-8" /> {searchTerm && ( )}
{importable.length > 0 && (
{selected.size > 0 && ( )} {batchProgress && ( <> {batchProgress.done}/{batchProgress.total} )}
)} {error && (
{error}
)} {!loading && pets.length === 0 && !error && (

No pets found

)} {pets.length > 0 && (
{pets.map((p) => { const isSelected = selected.has(p.lib); return (
{!p.nitroExists && ( )}
{p.lib}
{p.nitroExists ? (
Imported
) : ( )}
); })}
)}
); }