import { useState, useRef } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { Upload, FileText, Image as ImageIcon, Download, Trash2, AlertCircle, ExternalLink, } from "lucide-react"; import { attachmentsApi, type AttachmentEntityType, type AttachmentItem, } from "@/api/attachments"; import { ApiError } from "@/api/client"; import { formatDateTime } from "@/lib/format"; import { validateAttachmentFile } from "@/lib/validation"; import { Button } from "@/components/ui/button"; function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(2)} MB`; } interface AttachmentsProps { entityType: AttachmentEntityType; entityId: number; canUpload: boolean; canDelete: boolean; } export function Attachments({ entityType, entityId, canUpload, canDelete, }: AttachmentsProps) { const qc = useQueryClient(); const fileInputRef = useRef(null); const [dragActive, setDragActive] = useState(false); const [errorMsg, setErrorMsg] = useState(null); const [confirmDeleteId, setConfirmDeleteId] = useState(null); const queryKey = ["attachments", entityType, entityId]; const { data, isLoading } = useQuery({ queryKey, queryFn: () => attachmentsApi.list(entityType, entityId), enabled: Boolean(entityId), }); const uploadMutation = useMutation({ mutationFn: (file: File) => attachmentsApi.upload(entityType, entityId, file), onSuccess: () => { setErrorMsg(null); qc.invalidateQueries({ queryKey }); if (entityType === "asset") { qc.invalidateQueries({ queryKey: ["asset-overview", entityId] }); } }, onError: (err) => { setErrorMsg(err instanceof ApiError ? err.detail : "Failed to upload attachment."); }, }); const deleteMutation = useMutation({ mutationFn: (id: number) => attachmentsApi.remove(id), onSuccess: () => { setConfirmDeleteId(null); setErrorMsg(null); qc.invalidateQueries({ queryKey }); if (entityType === "asset") { qc.invalidateQueries({ queryKey: ["asset-overview", entityId] }); } }, onError: (err) => { setErrorMsg(err instanceof ApiError ? err.detail : "Failed to delete attachment."); }, }); function handleFiles(files: FileList | null) { if (!files || files.length === 0) return; const file = files[0]; const validationError = validateAttachmentFile(file); if (validationError) { setErrorMsg(validationError); return; } setErrorMsg(null); uploadMutation.mutate(file); } async function handleDownload(att: AttachmentItem, preview = false) { try { setErrorMsg(null); await attachmentsApi.download(att.id, att.original_name, preview); } catch (err) { setErrorMsg(err instanceof ApiError ? err.detail : "Failed to download file."); } } const items = data?.items ?? []; return (
{errorMsg && (
{errorMsg}
)} {canUpload && (
{ e.preventDefault(); setDragActive(true); }} onDragLeave={() => setDragActive(false)} onDrop={(e) => { e.preventDefault(); setDragActive(false); handleFiles(e.dataTransfer.files); }} className={`border-2 border-dashed rounded-lg p-5 text-center transition-colors ${ dragActive ? "border-[#1e3a8a] bg-blue-50/50" : "border-gray-300 bg-gray-50/50 hover:border-gray-400" }`} > { handleFiles(e.target.files); e.target.value = ""; }} />

Drag and drop a file here, or{" "}

Allowed: JPG, PNG, PDF • Max size: 10 MB

{uploadMutation.isPending && (

Uploading...

)}
)} {isLoading ? (
{[1, 2].map((i) => (
))}
) : items.length === 0 ? (
No attachments uploaded yet.
) : (
{items.map((att) => { const isPdf = att.mime_type === "application/pdf"; return (
{isPdf ? : }
{att.original_name}
{formatBytes(att.size_bytes)} {att.uploaded_by_name ? ` • Uploaded by ${att.uploaded_by_name}` : ""} {" • "} {formatDateTime(att.uploaded_at)}
{canDelete && ( confirmDeleteId === att.id ? (
) : ( ) )}
); })}
)}
); }