"use client"; import { useState, useEffect } from "react"; import { Download, Loader2, Music, Disc, X, Trash2 } from "lucide-react"; import { api } from "@/lib/api"; import { cn } from "@/utils/cn"; import { GradientSpinner } from "../ui/GradientSpinner"; interface ActiveDownload { id: string; subject: string; type: string; status: string; createdAt: string; } export function ActiveDownloadsTab() { const [downloads, setDownloads] = useState([]); const [loading, setLoading] = useState(true); const [cancelling, setCancelling] = useState>(new Set()); const fetchDownloads = async () => { try { const data = await api.getActiveDownloads(); setDownloads(data); } catch (error) { console.error("Failed to fetch active downloads:", error); } finally { setLoading(false); } }; const handleCancel = async (id: string) => { setCancelling(prev => new Set(prev).add(id)); try { await api.deleteDownload(id); // Optimistically remove from list setDownloads(prev => prev.filter(d => d.id !== id)); } catch (error) { console.error("Failed to cancel download:", error); } finally { setCancelling(prev => { const next = new Set(prev); next.delete(id); return next; }); } }; const handleCancelAll = async () => { const ids = downloads.map(d => d.id); setCancelling(new Set(ids)); try { // Cancel all downloads in parallel await Promise.all(ids.map(id => api.deleteDownload(id))); setDownloads([]); } catch (error) { console.error("Failed to cancel all downloads:", error); // Refresh to get actual state fetchDownloads(); } finally { setCancelling(new Set()); } }; useEffect(() => { fetchDownloads(); // Poll for updates every 5 seconds const interval = setInterval(fetchDownloads, 5000); return () => clearInterval(interval); }, []); const formatTime = (dateStr: string) => { const date = new Date(dateStr); const now = new Date(); const diff = now.getTime() - date.getTime(); if (diff < 60000) return "Just started"; if (diff < 3600000) return `${Math.floor(diff / 60000)}m`; if (diff < 86400000) return `${Math.floor(diff / 3600000)}h`; return date.toLocaleDateString(); }; if (loading) { return (
); } if (downloads.length === 0) { return (

No active downloads

Downloads will appear here

); } return (
{/* Header */}
{downloads.length} downloading
Active
{/* Download list */}
{downloads.map((download) => (
{cancelling.has(download.id) ? ( ) : ( )}

{download.subject}

{download.status} {download.type === "album" ? ( ) : ( )} {download.type} {formatTime(download.createdAt)}
))}
); }