"use client"; import { useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Download, FileText, Loader2, Upload } from "lucide-react"; import { AppHeader } from "@/components/layout/app-header"; import { PageHeader } from "@/components/layout/page-header"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { useStoredUser } from "@/lib/auth"; import { downloadTemplate, getTemplates, uploadTemplate } from "@/lib/api"; import type { DocumentTemplate } from "@/lib/models"; export default function TemplatesPage() { const router = useRouter(); const { user, ready } = useStoredUser(); const [templates, setTemplates] = useState([]); const [loading, setLoading] = useState(true); const [downloadingKey, setDownloadingKey] = useState(null); const [uploadingKey, setUploadingKey] = useState(null); const fileInputRef = useRef(null); const uploadTargetKey = useRef(null); useEffect(() => { if (!ready) return; if (!user || user.role === "CLIENT") { router.push("/dashboard"); return; } getTemplates() .then(setTemplates) .catch((error: Error) => { if (error.message === "Unauthorized") { router.push("/login"); } else { console.error(error); } }) .finally(() => setLoading(false)); }, [ready, user, router]); const handleDownload = async (template: DocumentTemplate) => { setDownloadingKey(template.key); try { await downloadTemplate(template.key, template.fileName); } catch (error) { console.error("Failed to download template:", error); } finally { setDownloadingKey(null); } }; const openUploadPicker = (key: string) => { uploadTargetKey.current = key; fileInputRef.current?.click(); }; const handleFileSelected = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; const key = uploadTargetKey.current; e.target.value = ""; if (!file || !key) return; setUploadingKey(key); try { const updated = await uploadTemplate(key, file); setTemplates((prev) => prev.map((t) => (t.key === key ? updated : t))); } catch (error) { console.error("Failed to upload template:", error); alert("Impossibile caricare il file"); } finally { setUploadingKey(null); } }; if (!ready || loading) { return (
); } if (!user || user.role === "CLIENT") { return null; } return (
{templates.length === 0 ? (
Nessun modello disponibile
) : ( templates.map((template) => ( {template.name}

{template.fileName}

{template.updatedAt && (

Ultimo aggiornamento: {new Date(template.updatedAt).toLocaleString("it-IT")}

)}
{user.role === "ADMIN" && ( )}
)) )}
); }