"use client"; import React, { useState, useEffect } from 'react'; import { FileText, Image, File, Trash2, Download, Loader2, FileSpreadsheet, FileArchive, FileVideo, FileAudio, FilePlus } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { useSession } from 'next-auth/react'; import { toast } from '@/components/ui/use-toast'; import { FileUpload } from './file-upload'; interface Attachment { id: string; filename: string; filePath: string; fileType: string; fileSize: number; createdAt: string; } interface AttachmentsListProps { missionId: string; initialAttachments?: Attachment[]; allowUpload?: boolean; allowDelete?: boolean; onAttachmentAdded?: (attachment: Attachment) => void; onAttachmentDeleted?: (attachmentId: string) => void; } export function AttachmentsList({ missionId, initialAttachments = [], allowUpload = true, allowDelete = true, onAttachmentAdded, onAttachmentDeleted }: AttachmentsListProps) { const { data: session } = useSession(); const [attachments, setAttachments] = useState(initialAttachments); const [isLoading, setIsLoading] = useState(false); const [deleteAttachment, setDeleteAttachment] = useState(null); const [showUpload, setShowUpload] = useState(false); // Fetch attachments for the mission if not provided initially useEffect(() => { if (initialAttachments.length === 0) { fetchAttachments(); } }, [missionId]); const fetchAttachments = async () => { if (!missionId || !session?.user?.id) return; setIsLoading(true); try { const response = await fetch(`/api/missions/${missionId}/attachments`); if (!response.ok) { throw new Error('Failed to fetch attachments'); } const data = await response.json(); setAttachments(data); } catch (error) { console.error('Error fetching attachments:', error); toast({ title: 'Error', description: 'Failed to load attachments', variant: 'destructive', }); } finally { setIsLoading(false); } }; const handleAttachmentUploaded = (data: any) => { if (data?.attachment) { setAttachments(prev => [...prev, data.attachment]); setShowUpload(false); if (onAttachmentAdded) { onAttachmentAdded(data.attachment); } } }; const handleAttachmentDelete = async () => { if (!deleteAttachment) return; try { const response = await fetch(`/api/missions/${missionId}/attachments/${deleteAttachment.id}`, { method: 'DELETE', }); if (!response.ok) { throw new Error('Failed to delete attachment'); } setAttachments(prev => prev.filter(a => a.id !== deleteAttachment.id)); if (onAttachmentDeleted) { onAttachmentDeleted(deleteAttachment.id); } toast({ title: 'Success', description: 'Attachment deleted successfully', variant: 'default', }); } catch (error) { console.error('Error deleting attachment:', error); toast({ title: 'Error', description: 'Failed to delete attachment', variant: 'destructive', }); } finally { setDeleteAttachment(null); } }; const getFileIcon = (fileType: string) => { if (fileType.startsWith('image/')) { return ; } else if (fileType.includes('pdf')) { return ; } else if (fileType.includes('spreadsheet') || fileType.includes('excel') || fileType.includes('csv')) { return ; } else if (fileType.includes('zip') || fileType.includes('compressed')) { return ; } else if (fileType.includes('video')) { return ; } else if (fileType.includes('audio')) { return ; } else { return ; } }; const formatFileSize = (bytes: number): string => { if (bytes < 1024) { return `${bytes} B`; } else if (bytes < 1024 * 1024) { return `${(bytes / 1024).toFixed(1)} KB`; } else { return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } }; return (
{(allowUpload && !showUpload) && (
)} {showUpload && (

Upload New Attachment

)} {isLoading ? (
) : attachments.length === 0 ? (

No attachments yet

{allowUpload && ( )}
) : (
    {attachments.map((attachment) => (
  • {getFileIcon(attachment.fileType)}

    {attachment.filename}

    {formatFileSize(attachment.fileSize)} • {new Date(attachment.createdAt).toLocaleDateString()}

    {allowDelete && ( )}
  • ))}
)} !open && setDeleteAttachment(null)}> Delete Attachment Are you sure you want to delete "{deleteAttachment?.filename}"? This action cannot be undone. Cancel Delete
); }