"use client"; import type { Anexo } from "@prisma/client"; import { Download, FileUp, Trash2 } from "lucide-react"; import { useRef, useState } from "react"; import { useFormContext } from "react-hook-form"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { formatFileSize } from "@/lib/format"; type FormValues = { perguntas: Record< string, { texto?: string; selecionadas?: string[]; complemento?: string; } >; }; type Props = { briefingId: string; perguntaId: string; anexos: Pick[]; readOnly?: boolean; }; export function AnexoField({ briefingId, perguntaId, anexos, readOnly = false }: Props) { const form = useFormContext(); const [items, setItems] = useState(anexos); const [uploading, setUploading] = useState(false); const [message, setMessage] = useState(null); const fileInputRef = useRef(null); const fieldName = `perguntas.${perguntaId}`; const selected = form.watch(`${fieldName}.selecionadas`) ?? []; const checked = selected.includes("Estou enviando este material"); async function uploadFile(file: File) { setUploading(true); setMessage(null); const data = new FormData(); data.append("file", file); try { const response = await fetch(`/api/briefings/${briefingId}/perguntas/${perguntaId}/anexos`, { method: "POST", body: data }); const payload = await response.json(); if (!response.ok) { setMessage(payload.message ?? "Nao foi possivel enviar o arquivo."); return; } setItems((current) => [payload.anexo, ...current]); setMessage("Arquivo enviado."); } finally { setUploading(false); if (fileInputRef.current) { fileInputRef.current.value = ""; } } } async function removeFile(id: string) { setMessage(null); const response = await fetch(`/api/anexos/${id}`, { method: "DELETE" }); const payload = await response.json(); if (!response.ok) { setMessage(payload.message ?? "Nao foi possivel remover o arquivo."); return; } setItems((current) => current.filter((item) => item.id !== id)); } return (