178 lines
5.8 KiB
TypeScript
178 lines
5.8 KiB
TypeScript
"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<Anexo, "id" | "nomeOriginal" | "mime" | "tamanho">[];
|
|
readOnly?: boolean;
|
|
};
|
|
|
|
export function AnexoField({ briefingId, perguntaId, anexos, readOnly = false }: Props) {
|
|
const form = useFormContext<FormValues>();
|
|
const [items, setItems] = useState(anexos);
|
|
const [uploading, setUploading] = useState(false);
|
|
const [message, setMessage] = useState<string | null>(null);
|
|
const fileInputRef = useRef<HTMLInputElement>(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 (
|
|
<div className="space-y-4">
|
|
<label className="flex items-start gap-3 rounded-md border p-3 text-sm leading-6">
|
|
<Checkbox
|
|
checked={checked}
|
|
disabled={readOnly}
|
|
onCheckedChange={(value) => {
|
|
form.setValue(
|
|
`${fieldName}.selecionadas`,
|
|
value ? ["Estou enviando este material"] : [],
|
|
{ shouldDirty: true }
|
|
);
|
|
}}
|
|
/>
|
|
<span>Estou enviando este material</span>
|
|
</label>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor={`links-${perguntaId}`}>Links dos materiais</Label>
|
|
<Textarea
|
|
id={`links-${perguntaId}`}
|
|
rows={4}
|
|
disabled={readOnly}
|
|
placeholder="Cole links do Drive, Dropbox, YouTube ou outros locais seguros."
|
|
{...form.register(`${fieldName}.texto`)}
|
|
/>
|
|
</div>
|
|
|
|
<div className="rounded-md border border-dashed bg-muted/40 p-4">
|
|
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
|
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
|
<FileUp className="h-5 w-5 text-primary" />
|
|
<span>Envie arquivos relacionados a este item.</span>
|
|
</div>
|
|
{!readOnly ? (
|
|
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInputRef.current?.click()}>
|
|
{uploading ? "Enviando..." : "Selecionar arquivo"}
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
<input
|
|
ref={fileInputRef}
|
|
type="file"
|
|
accept=".png,.jpg,.jpeg,.webp,.svg,.pdf,.docx,.doc,.xlsx,.xls,.pptx,.zip,.mp4,.mov"
|
|
className="hidden"
|
|
disabled={readOnly}
|
|
onChange={(event) => {
|
|
const file = event.target.files?.[0];
|
|
|
|
if (file) {
|
|
void uploadFile(file);
|
|
}
|
|
}}
|
|
/>
|
|
<p className="mt-3 text-xs leading-5 text-muted-foreground">
|
|
Nao envie senhas. Informe apenas provedores e responsaveis.
|
|
</p>
|
|
{uploading ? (
|
|
<div className="mt-3 h-2 overflow-hidden rounded-full bg-muted">
|
|
<div className="h-full w-2/3 animate-pulse rounded-full bg-primary" />
|
|
</div>
|
|
) : null}
|
|
{message ? <p className="mt-3 text-sm text-muted-foreground">{message}</p> : null}
|
|
</div>
|
|
|
|
{items.length > 0 ? (
|
|
<div className="space-y-2">
|
|
{items.map((anexo) => (
|
|
<div key={anexo.id} className="flex flex-col gap-3 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between">
|
|
<div>
|
|
<p className="text-sm font-medium">{anexo.nomeOriginal}</p>
|
|
<p className="text-xs text-muted-foreground">{formatFileSize(anexo.tamanho)} | {anexo.mime}</p>
|
|
</div>
|
|
<div className="flex gap-2">
|
|
<Button asChild variant="outline" size="sm">
|
|
<a href={`/api/anexos/${anexo.id}`}>
|
|
<Download className="mr-2 h-4 w-4" />
|
|
Baixar
|
|
</a>
|
|
</Button>
|
|
{!readOnly ? (
|
|
<Button type="button" variant="outline" size="sm" onClick={() => removeFile(anexo.id)}>
|
|
<Trash2 className="mr-2 h-4 w-4" />
|
|
Remover
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|