import React, { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { Download, X, Maximize, Minimize, AlertCircle, Loader2, Info } from "lucide-react"; import { toast } from "sonner"; import { Attachment, attachmentApi } from '@/services/attachmentApi'; import { cn } from '@/lib/utils'; import CustomDialog from '@/components/CustomDialog'; interface AttachmentViewerDialogProps { isOpen: boolean; onClose: () => void; attachment: Attachment | null; onDownload: (attachment: Attachment) => void; } const AttachmentViewerDialog: React.FC = ({ isOpen, onClose, attachment, onDownload }) => { const [fileUrl, setFileUrl] = useState(null); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [isFullscreen, setIsFullscreen] = useState(false); useEffect(() => { const loadFile = async () => { if (!attachment || !isOpen) return; setIsLoading(true); setError(null); try { // Use the attachmentApi directly to download the file const result = await attachmentApi.download(attachment.attachmentId); const objectUrl = URL.createObjectURL(result.blob); setFileUrl(objectUrl); } catch (err) { console.error('Error loading file:', err); setError('Failed to load the file for preview. Please try downloading instead.'); } finally { setIsLoading(false); } }; loadFile(); // Cleanup function to revoke the object URL when component unmounts or dialog closes return () => { if (fileUrl) { URL.revokeObjectURL(fileUrl); setFileUrl(null); } }; }, [attachment, isOpen]); const toggleFullscreen = () => { setIsFullscreen(!isFullscreen); }; const handleDownload = () => { if (attachment) { onDownload(attachment); } }; const isImage = attachment?.fileType?.startsWith('image/') || attachment?.fileName?.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i); const isPdf = attachment?.fileType === 'application/pdf' || attachment?.fileName?.endsWith('.pdf'); const isText = attachment?.fileType?.startsWith('text/') || attachment?.fileName?.match(/\.(txt|md|rtf|json|xml|html|css|js|ts)$/i); return (
{attachment?.createdBy && Added by {attachment.createdBy}} {attachment?.createdAt && attachment?.createdBy && ยท } {attachment?.createdAt && {new Date(attachment.createdAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })} }
{/* File description */} {attachment?.description && (

{attachment.description}

)}
{isLoading ? (

Loading preview...

) : error ? (

{error}

) : fileUrl && isImage ? ( {attachment?.fileName ) : fileUrl && isPdf ? (