'use client'; import { useEffect, useState } from 'react'; import Modal from './Modal'; import { getAvailableDownloads, deleteDownload } from '@/app/actions/get-available-downloads'; interface DownloadFile { name: string; url: string; size: number; } function formatFileSize(bytes: number): string { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } interface DatasetDownloadsModalProps { datasetId: number; } export default function DatasetDownloadsModal({ datasetId }: DatasetDownloadsModalProps) { const [isOpen, setIsOpen] = useState(false); const [downloads, setDownloads] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [deleting, setDeleting] = useState(null); const fetchDownloads = async () => { try { setLoading(true); setError(null); const files = await getAvailableDownloads(datasetId); setDownloads(files); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load downloads'); } finally { setLoading(false); } }; const handleOpenModal = () => { setIsOpen(true); if (downloads.length === 0) { fetchDownloads(); } }; const handleDelete = async (fileName: string) => { if (!confirm(`Are you sure you want to delete "${fileName}"?`)) { return; } setDeleting(fileName); try { await deleteDownload(fileName); setDownloads(downloads.filter(d => d.name !== fileName)); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to delete download'); } finally { setDeleting(null); } }; return ( <> setIsOpen(false)} title="Available Downloads"> {loading ? (
Loading available downloads...
) : error ? (
Error: {error}
) : downloads.length === 0 ? (
No downloads available for this dataset
) : (
{downloads.map((download) => (
{download.name}
{formatFileSize(download.size)}
Download
))}
)}
); }