"use client";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import EmptyState from "@/components/EmptyState";
import Icon from "@/components/Icon";
import Modal from "@/components/Modal";
import { useToast } from "@/components/Toast";
import { api, restoreAt } from "@/lib/client";
import type { CollectionDTO } from "@/lib/types";
import { COLLECTION_COLORS, cn, formatDate } from "@/lib/utils";
const isPending = (id: string) => id.startsWith("temp-");
function ColorPicker({ value, onChange, size = "sm" }: { value: string; onChange: (c: string) => void; size?: "sm" | "md" }) {
return (
{COLLECTION_COLORS.map((c) => (
);
}
export default function CollectionsManager({ initial }: { initial: CollectionDTO[] }) {
const [items, setItems] = useState(initial);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [color, setColor] = useState(COLLECTION_COLORS[0]);
const [creating, setCreating] = useState(false);
const [editing, setEditing] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
const confirmTimer = useRef | null>(null);
const { toast } = useToast();
useEffect(
() => () => {
if (confirmTimer.current) clearTimeout(confirmTimer.current);
},
[],
);
const create = async () => {
const cleanName = name.trim();
if (!cleanName || creating) return;
setCreating(true);
const now = new Date().toISOString();
const optimistic: CollectionDTO = {
id: `temp-${Date.now()}`,
name: cleanName,
description: description.trim(),
color,
itemCount: 0,
createdAt: now,
updatedAt: now,
};
setItems((cur) => [optimistic, ...cur]);
const res = await api<{ item: CollectionDTO }>("/api/collections", {
method: "POST",
body: { name: optimistic.name, description: optimistic.description, color },
});
setCreating(false);
if (!res.ok || !res.data) {
setItems((cur) => cur.filter((c) => c.id !== optimistic.id));
toast(res.error ?? "Could not create the collection.", "error");
return;
}
const created = res.data.item;
setItems((cur) => cur.map((c) => (c.id === optimistic.id ? created : c)));
setName("");
setDescription("");
toast(`Collection “${created.name}” created`);
};
const saveEdit = async (original: CollectionDTO, patch: { name: string; description: string; color: string }) => {
setItems((cur) => cur.map((c) => (c.id === original.id ? { ...c, ...patch } : c)));
setEditing(null);
const res = await api(`/api/collections/${original.id}`, { method: "PATCH", body: patch });
if (!res.ok) {
setItems((cur) => cur.map((c) => (c.id === original.id ? original : c)));
toast(res.error ?? "Could not save changes.", "error");
return;
}
toast("Collection updated");
};
const remove = async (item: CollectionDTO) => {
if (confirmDelete !== item.id) {
if (confirmTimer.current) clearTimeout(confirmTimer.current);
setConfirmDelete(item.id);
confirmTimer.current = setTimeout(() => setConfirmDelete(null), 4000);
return;
}
if (confirmTimer.current) clearTimeout(confirmTimer.current);
setConfirmDelete(null);
const index = items.findIndex((c) => c.id === item.id);
setItems((cur) => cur.filter((c) => c.id !== item.id));
const res = await api(`/api/collections/${item.id}`, { method: "DELETE" });
if (!res.ok && res.status !== 404) {
setItems((cur) => restoreAt(cur, item, index));
toast(res.error ?? "Could not delete the collection.", "error");
return;
}
toast("Collection deleted — its saved items were kept");
};
return (
{items.length === 0 ? (
) : (
{items.map((c) => {
const pending = isPending(c.id);
return (
{!pending && (
)}
{pending ? (
c.name
) : (
{c.name}
)}
{c.description && (
{c.description}
)}
{c.itemCount} {c.itemCount === 1 ? "item" : "items"}
{pending ? "saving…" : `created ${formatDate(c.createdAt)}`}
{confirmDelete === c.id && (
Click the trash icon again to delete. Saved items are kept.
)}
);
})}
)}
{editing && (
setEditing(null)}
onSave={(patch) => saveEdit(editing, patch)}
/>
)}
);
}
function EditCollectionModal({
collection,
onClose,
onSave,
}: {
collection: CollectionDTO;
onClose: () => void;
onSave: (patch: { name: string; description: string; color: string }) => void;
}) {
const [name, setName] = useState(collection.name);
const [description, setDescription] = useState(collection.description);
const [color, setColor] = useState(collection.color);
const canSave = name.trim().length > 0;
return (
>
}
>
);
}