import { useState } from 'react'
import { useLibrary } from './useLibrary'
import { libraryApi } from './api'
import { Link, useNavigate } from 'react-router-dom'
import { formatDistanceToNow } from 'date-fns'
import { ContextMenu } from './ContextMenu'
export const DocumentGrid = ({ isTrash }: { isTrash: boolean }) => {
const { documents, selectedIds, isLoading, error, toggleSelection, deleteDocument, restoreDocument, updateDocument } = useLibrary()
const navigate = useNavigate()
const [contextMenu, setContextMenu] = useState<{ x: number, y: number, docId: string } | null>(null)
const handleContextMenu = (e: React.MouseEvent, docId: string) => {
e.preventDefault()
setContextMenu({ x: e.clientX, y: e.clientY, docId })
}
if (isLoading) {
return (
)
}
if (error) {
return (
{error}
)
}
if (documents.length === 0) {
return (
📄
{isTrash ? 'Trash is empty' : 'No documents yet'}
{isTrash ? 'Nothing to see here.' : 'Drag & drop a PDF, or click Upload to get started.'}
)
}
return (
<>
{documents.map((doc) => {
const isSelected = selectedIds.has(doc.id)
const thumbnailUrl = libraryApi.getThumbnailUrl(doc.id)
return (
handleContextMenu(e, doc.id)}
className={`group relative flex flex-col bg-white dark:bg-gray-800 rounded-3xl overflow-hidden shadow-sm hover:shadow-xl hover:shadow-accent-500/10 transition-all duration-300 border border-gray-200 dark:border-gray-700 hover:-translate-y-1 ${
isSelected ? 'border-accent-500 shadow-md ring-2 ring-accent-500/50 scale-[1.02]' : 'hover:border-accent-300 dark:hover:border-accent-700'
}`}
>
{isSelected && (
)}
{
if (isTrash) e.preventDefault() // disable link in trash
}}
>

{
// Fallback if no thumbnail
const target = e.target as HTMLImageElement;
target.onerror = null;
target.src = 'data:image/svg+xml;utf8,
';
}}
/>
{/* Hover overlay */}
{doc.title}
{formatDistanceToNow(new Date(doc.updated_at), { addSuffix: true })}
{(doc.size_bytes / 1024 / 1024).toFixed(1)} MB
)
})}
{contextMenu && (
setContextMenu(null)}
onOpen={() => navigate(`/editor/${contextMenu.docId}`)}
onRename={() => {
const doc = documents.find(d => d.id === contextMenu.docId)
if (doc) {
const newTitle = window.prompt("Rename Document:", doc.title)
if (newTitle && newTitle.trim() !== "" && newTitle !== doc.title) {
updateDocument(doc.id, { title: newTitle.trim() })
}
}
}}
onDelete={() => {
if (window.confirm('Move this document to Trash?')) void deleteDocument(contextMenu.docId)
}}
onRestore={() => restoreDocument(contextMenu.docId)}
onHardDelete={() => {
if (window.confirm('Delete this document permanently? This cannot be undone.')) void deleteDocument(contextMenu.docId, true)
}}
/>
)}
>
)
}