import { useRef, useState } from "react"; import { useMutation } from "@tanstack/react-query"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Upload, UploadCloud } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { useToast } from "@/hooks/use-toast"; export function ImportDatabaseSection() { const { toast } = useToast(); const fileInputRef = useRef(null); const [selectedFile, setSelectedFile] = useState(null); const [confirmOpen, setConfirmOpen] = useState(false); const restoreMutation = useMutation({ mutationFn: async (file: File) => { const formData = new FormData(); formData.append("file", file); const token = localStorage.getItem("token"); const res = await fetch("/api/database-management/restore", { method: "POST", headers: token ? { Authorization: `Bearer ${token}` } : {}, body: formData, }); if (!res.ok) { const body = await res.json().catch(() => ({})); throw new Error(body.error || "Restore failed"); } return res.json(); }, onSuccess: () => { toast({ title: "Database Restored", description: "The database has been successfully restored from the backup file.", }); setSelectedFile(null); if (fileInputRef.current) fileInputRef.current.value = ""; }, onError: (err: any) => { toast({ title: "Restore Failed", description: err.message, variant: "destructive", }); }, }); const handleFileChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0] ?? null; setSelectedFile(file); }; const handleImportClick = () => { if (!selectedFile) return; setConfirmOpen(true); }; const handleConfirm = () => { setConfirmOpen(false); if (selectedFile) restoreMutation.mutate(selectedFile); }; return ( <> Import Database

Restore the database from a .sql backup file. This will overwrite all existing data.

{selectedFile && (

Selected: {selectedFile.name}{" "} ({(selectedFile.size / 1024 / 1024).toFixed(1)} MB)

)}
Restore database? This will overwrite all existing data with the contents of{" "} {selectedFile?.name}. This action cannot be undone. Cancel Yes, restore ); }