"use client" import { useState, useRef } from "react" import { useRouter } from "next/navigation" import { toast } from "sonner" import { Camera, Loader2, X } from "lucide-react" interface Props { propertyId: string currentImageUrl?: string | null } export function PropertyPhotoUpload({ propertyId, currentImageUrl }: Props) { const router = useRouter() const fileRef = useRef(null) const [uploading, setUploading] = useState(false) const [preview, setPreview] = useState(currentImageUrl ?? null) async function handleFile(e: React.ChangeEvent) { const file = e.target.files?.[0] if (!file) return if (!file.type.startsWith("image/")) { toast.error("Please select an image file") return } if (file.size > 5 * 1024 * 1024) { toast.error("Image must be under 5MB") return } setUploading(true) try { // Upload to local storage via the gated upload endpoint const uploadData = new FormData() uploadData.append("file", file) uploadData.append("scope", "property-images") uploadData.append("fixed_name", propertyId) const uploadRes = await fetch("/api/upload", { method: "POST", body: uploadData }) if (!uploadRes.ok) throw new Error("Upload failed") const { url: publicUrl } = await uploadRes.json() // Update property record const res = await fetch(`/api/properties/${propertyId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ image_url: publicUrl }), }) if (!res.ok) throw new Error("Failed to save image URL") setPreview(publicUrl) toast.success("Photo updated") router.refresh() } catch (err: any) { toast.error(err.message ?? "Upload failed") } finally { setUploading(false) } } async function removePhoto() { setUploading(true) try { const res = await fetch(`/api/properties/${propertyId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ image_url: null }), }) if (!res.ok) throw new Error("Failed to remove photo") setPreview(null) toast.success("Photo removed") router.refresh() } catch { toast.error("Failed to remove photo") } finally { setUploading(false) } } return (
{preview ? (
Property
{uploading && (
)}
) : ( )}
) }