import { useState, useMemo, useEffect } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useCollection, useDeleteCollection, useGetCollectionParts, useRemoveEntryFromCollection, } from "@/hooks/useCollections"; import { EntryLibraryGrid } from "@/components/entries/EntryLibraryGrid"; import { getCollectionPosterUrl, getBackdropUrl } from "@/lib/media-utils"; import { getTmdbImageUrl } from "@/lib/api"; import { Skeleton } from "@/components/ui/skeleton"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Star, MoreVertical, Pencil, Download, Trash2, ArrowUp, ArrowDown, Eye, EyeOff, } from "lucide-react"; import { CollectionEditDialog } from "@/components/dialogs/CollectionEditDialog"; import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog"; import { toast } from "sonner"; import type { Entry } from "@/types"; import { useCollectionSortStore, type CollectionSortField, type SortDir, } from "@/stores/useCollectionSortStore"; export function CollectionDetailsPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const { data: collection, isLoading, isError } = useCollection(Number(id)); const [showEditDialog, setShowEditDialog] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const collectionSortPrefs = useCollectionSortStore((s) => s.prefs); const setSortPref = useCollectionSortStore((s) => s.setSort); const setHideUnseen = useCollectionSortStore((s) => s.setHideUnseen); const collectionId = Number(id); const sortPref = collectionSortPrefs[collectionId]; const sortField: CollectionSortField = sortPref?.field ?? "order"; const sortDir: SortDir = sortPref?.dir ?? "asc"; const hideUnseen = sortPref?.hideUnseen ?? false; const deleteCollection = useDeleteCollection(); const getCollectionParts = useGetCollectionParts(); const removeEntryFromCollection = useRemoveEntryFromCollection(); const entries = useMemo( () => (collection?.entries || []).map((e) => ({ ...e, isInLibrary: true })), [collection?.entries], ); const sortedEntries = useMemo(() => { return [...entries].sort((a, b) => { let cmp = 0; switch (sortField) { case "order": { const oa = (a as Entry & { UserCollectionEntry?: { order: number } }) .UserCollectionEntry?.order ?? 0; const ob = (b as Entry & { UserCollectionEntry?: { order: number } }) .UserCollectionEntry?.order ?? 0; cmp = oa - ob; break; } case "year": { const ya = a.release_date ? new Date(a.release_date).getFullYear() : 0; const yb = b.release_date ? new Date(b.release_date).getFullYear() : 0; cmp = ya - yb; break; } case "title": cmp = (a.title || "").localeCompare(b.title || ""); break; case "rating": { const ra = a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0; const rb = b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0; cmp = ra - rb; break; } } return sortDir === "asc" ? cmp : -cmp; }); }, [entries, sortField, sortDir]); // Fallback backdrop: use first entry's backdrop if collection has none const backdropUrl = useMemo(() => { if (collection?.backdrop_path) return getTmdbImageUrl(collection.backdrop_path, "w1280"); // Try to find a backdrop from one of the entries const entryWithBackdrop = entries.find((e) => e.banner_path); if (entryWithBackdrop?.banner_path) return getTmdbImageUrl(entryWithBackdrop.banner_path, "w1280"); // Try entry medias for (const e of entries) { const url = getBackdropUrl(e); if (url) return url; } return null; }, [collection?.backdrop_path, entries]); const handleSort = (field: CollectionSortField) => { if (field === sortField) { setSortPref(collectionId, field, sortDir === "asc" ? "desc" : "asc"); } else { setSortPref(collectionId, field, field === "rating" ? "desc" : "asc"); } }; // ── Computed stats (from already-fetched data) ── const stats = useMemo(() => { const movies = entries.filter((e) => !e.is_tvseries); const tvEntries = entries.filter((e) => e.is_tvseries); const seasonCount = tvEntries.reduce( (sum, e) => sum + (e.seasons?.length || 0), 0, ); const episodeCount = tvEntries.reduce( (sum, e) => sum + (e.seasons?.reduce((s, season) => s + (season.episode_count || 0), 0) || 0), 0, ); const typeParts: string[] = []; if (movies.length > 0) typeParts.push(`${movies.length} movies`); if (tvEntries.length > 0) typeParts.push(`${tvEntries.length} series`); const typeStr = typeParts.join(" & "); const subParts: string[] = []; if (seasonCount > 0) subParts.push(`${seasonCount} seasons`); if (episodeCount > 0) subParts.push(`${episodeCount} episodes`); const subStr = subParts.length > 0 ? ` (${subParts.join("/")})` : ""; const summary = `${entries.length} entries - ${typeStr}${subStr}`; const watchMinutes = entries.reduce((sum, e) => { if (e.is_tvseries) { const eps = e.seasons?.reduce( (s, season) => s + (season.episode_count || 0), 0, ) || 0; const epRuntime = e.runtime || 42; return sum + eps * epRuntime; } return sum + (e.runtime || 0); }, 0); const hours = Math.floor(watchMinutes / 60); const mins = watchMinutes % 60; const watchTime = hours > 0 ? `${hours}h ${mins}m` : `${mins}m`; return { summary, watchTime }; }, [entries]); // Handle error redirect in useEffect (not during render) useEffect(() => { if (!isLoading && (isError || (!collection && !isLoading))) { toast.error("Collection not found"); navigate("/collections", { replace: true }); } }, [isLoading, isError, collection, navigate]); if (isLoading) { return (
{Array.from({ length: 6 }).map((_, i) => ( ))}
); } if (!collection) return null; const handleDelete = () => { deleteCollection.mutate(collection.id, { onSuccess: () => navigate("/collections", { replace: true }), }); }; const handleGetParts = () => { getCollectionParts.mutate(collection.id); }; return (
{/* Hero banner */}
{backdropUrl ? ( {collection.name} ) : (
)}
{/* Quick action menu - top right */}
setShowEditDialog(true)}> Edit {getCollectionParts.isPending ? "Fetching..." : "Get All Parts"} setShowDeleteConfirm(true)} > Delete
{collection.name}

{collection.name}

{collection.description && (

{collection.description}

)}
{stats.summary} ~{stats.watchTime} {collection.user_rating != null && collection.user_rating > 0 && (
{collection.user_rating}/10
)}
{/* Sort – bottom right */}
{entries.length > 1 && ( <> {(["order", "year", "title", "rating"] as const).map( (field) => ( ), )} )}
{/* Entries grid */} removeEntryFromCollection.mutate({ collectionId: collection.id, entryId, }) } /> {/* Edit dialog */} {showEditDialog && ( )} {/* Delete confirmation */}
); }