Files

70 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

"use client"
import { useState, useRef } from "react"
import { Upload, X, File, Loader2 } from "lucide-react"
interface FileUploadProps {
propertyId: string
onUploaded: (doc: { id: string; name: string; file_url: string; file_type: string; file_size: number }) => void
}
export function FileUpload({ propertyId, onUploaded }: FileUploadProps) {
const [dragging, setDragging] = useState(false)
const [uploading, setUploading] = useState(false)
const [error, setError] = useState("")
const inputRef = useRef<HTMLInputElement>(null)
async function upload(file: File) {
setUploading(true)
setError("")
const fd = new FormData()
fd.append("file", file)
fd.append("property_id", propertyId)
fd.append("name", file.name.replace(/\.[^/.]+$/, ""))
fd.append("category", "general")
const res = await fetch("/api/documents", { method: "POST", body: fd })
const data = await res.json()
setUploading(false)
if (!res.ok) {
setError(data.error ?? "Upload failed")
return
}
onUploaded(data)
}
function handleFiles(files: FileList | null) {
if (!files || files.length === 0) return
upload(files[0])
}
return (
<div className="space-y-2">
<div
onDragOver={(e) => { e.preventDefault(); setDragging(true) }}
onDragLeave={() => setDragging(false)}
onDrop={(e) => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files) }}
onClick={() => inputRef.current?.click()}
className={`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed px-6 py-10 transition ${
dragging ? "border-indigo-500 bg-indigo-500/5" : "border-white/10 bg-white/[0.02] hover:border-white/20"
}`}
>
<input ref={inputRef} type="file" className="hidden" onChange={(e) => handleFiles(e.target.files)} />
{uploading ? (
<Loader2 className="h-7 w-7 animate-spin text-indigo-400" />
) : (
<Upload className="h-7 w-7 text-white/30" />
)}
<p className="text-sm text-white/50">
{uploading ? "Uploading..." : "Drop a file here or click to browse"}
</p>
<p className="text-xs text-white/30">PDF, DOC, JPG, PNG max 20 MB</p>
</div>
{error && <p className="text-xs text-red-400">{error}</p>}
</div>
)
}