"use client"; import React, { useEffect, useState } from "react"; import { useForm, SubmitHandler } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { UploadButton } from "@/lib/uploadthing"; import { downloadSchema } from "@/lib/validations/validation"; import { useToast } from "@/components/ui/use-toast"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; interface DownloadEntry { _id: string; fileName: string; version: string; downloadLink: string; fileSize: string; } const DownloadsPage = () => { const { toast } = useToast(); const [downloads, setDownloads] = useState([]); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); const form = useForm>({ resolver: zodResolver(downloadSchema), defaultValues: { fileName: "", version: "", downloadLink: "", fileSize: "", }, }); const fetchDownloads = async () => { try { const response = await fetch("/api/downloads", { method: "GET", }); if (response.ok) { const data: DownloadEntry[] = await response.json(); setDownloads(data); } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error: any) { setError(error.message || "Failed to fetch downloads"); } }; useEffect(() => { fetchDownloads(); const interval = setInterval(() => { fetchDownloads(); }, 10000); return () => clearInterval(interval); }, []); const onSubmit: SubmitHandler> = async ( data ) => { setLoading(true); const response = await fetch("/api/upload", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); if (response.ok) { form.reset(); fetchDownloads(); setLoading(false); toast({ description: "Download Successfully Updated" }); } else { console.error("Upload failed"); setLoading(false); toast({ description: "Uploading Failed", variant: "destructive" }); } }; const deleteDownload = async (id: string) => { try { const response = await fetch(`/api/delete/downloads/${id}`, { method: "DELETE", }); if (response.ok) { fetchDownloads(); } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error: any) { setError(error.message || "Failed to delete download"); } }; return (

Downloads Form

( File Name )} /> ( Version )} /> ( Download Link { field.onChange(res[0].url); }} onUploadError={(error: Error) => { alert(`ERROR! ${error.message}`); }} /> )} /> ( File Size )} /> {/* Section to list and delete downloads */}

Existing Downloads

{error &&

{error}

} File Name Version Download Link File Size Actions {downloads .slice() .reverse() .map((download) => ( {download.fileName} {download.version} {download.downloadLink} {download.fileSize} ))}
); }; export default DownloadsPage;