import { useState } from "react"; import { Download, Loader2 } from "lucide-react"; import { toast } from "sonner"; import type { FileVersion } from "@/api/types"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { formatFileSize } from "@/lib/mediaFormat"; import { buildDirectDownloadUrl } from "@/hooks/queries/downloads"; import { buildQualitySummary, sortByResolution } from "@/pages/ItemDetail/components/VersionFlyout"; interface DownloadVersionPickerProps { open: boolean; onOpenChange: (open: boolean) => void; versions: FileVersion[]; title?: string; summaryBuilder?: (version: FileVersion) => string; } export default function DownloadVersionPicker({ open, onOpenChange, versions, title, summaryBuilder, }: DownloadVersionPickerProps) { const sorted = sortByResolution(versions); const [downloading, setDownloading] = useState(null); const handleDownload = async (version: FileVersion) => { const url = buildDirectDownloadUrl(version.file_id); setDownloading(version.file_id); try { const res = await fetch(url, { method: "HEAD" }); if (!res.ok) { if (res.status === 403) toast.error("You are not allowed to download this file"); else if (res.status === 429) toast.error("Download limit reached. Try again later"); else toast.error("Download failed. Try again later"); return; } const a = document.createElement("a"); a.href = url; a.download = ""; document.body.appendChild(a); a.click(); document.body.removeChild(a); onOpenChange(false); } catch { toast.error("Network error. Check your connection and try again"); } finally { setDownloading(null); } }; return ( Download{title ? `: ${title}` : ""} Choose a file to download. Make sure you have enough disk space.
{sorted.map((version) => { const quality = summaryBuilder?.(version) || buildQualitySummary(version); const size = summaryBuilder ? "" : formatFileSize(version.file_size); return ( ); })}
{sorted.length > 1 && (

Larger files require more storage space.

)}
); }