"use client"; import { useRef, useState } from "react"; import { getBackendErrorMessage } from "@/lib/error-message"; interface UploadFieldProps { label: string; value: string; accept?: string; helperText?: string; onUploaded: (fileId: string) => void; } function formatDisplayValue(value: string) { if (!value) { return ""; } if (value.startsWith("http://") || value.startsWith("https://")) { try { const url = new URL(value); const lastSegment = url.pathname.split("/").filter(Boolean).pop(); return lastSegment || url.hostname; } catch { return value; } } return value; } function getToken() { if (typeof window === "undefined") { return ""; } return sessionStorage.getItem("token") || localStorage.getItem("token") || ""; } export function UploadField({ label, value, accept, helperText, onUploaded, }: UploadFieldProps) { const inputRef = useRef(null); const [uploading, setUploading] = useState(false); const [error, setError] = useState(""); const [fileName, setFileName] = useState(""); const displayValue = formatDisplayValue(value); async function handleChange(event: React.ChangeEvent) { const file = event.target.files?.[0]; if (!file) { return; } setUploading(true); setError(""); try { const formData = new FormData(); formData.append("file", file); const res = await fetch("/api/upload", { method: "POST", headers: { "x-auth-token": getToken() }, body: formData, }); const data = await res.json(); if (!res.ok) { throw new Error(getBackendErrorMessage(data, "Upload gagal")); } const fileId = data?.data?.id || data?.data?.fileId || data?.fileId || ""; if (!fileId) { throw new Error("File id tidak ditemukan pada response upload"); } setFileName(file.name); onUploaded(fileId); } catch (err) { setError(err instanceof Error ? err.message : "Upload gagal"); } finally { setUploading(false); if (inputRef.current) { inputRef.current.value = ""; } } } return (

{label}

{value ? "Uploaded" : "No file uploaded"}

{fileName || (value ? `File: ${displayValue}` : helperText || "Select a file")}

{error ? (

{error}

) : null}
); }