"use client" import { useState } from "react" import { useRouter } from "next/navigation" import { toast } from "sonner" import { Select } from "@/components/ui/select" import type { Unit } from "@/types" const statusOptions = [ { value: "vacant", label: "Vacant" }, { value: "occupied", label: "Occupied" }, { value: "maintenance", label: "Maintenance" }, { value: "unavailable", label: "Unavailable" }, ] interface UnitFormProps { propertyId: string unit?: Unit onSuccess?: () => void } export function UnitForm({ propertyId, unit, onSuccess }: UnitFormProps) { const router = useRouter() const [loading, setLoading] = useState(false) const [status, setStatus] = useState(unit?.status ?? "vacant") const isEditing = Boolean(unit) async function handleSubmit(e: React.FormEvent) { e.preventDefault() setLoading(true) const formData = new FormData(e.currentTarget) const body = { property_id: propertyId, unit_number: formData.get("unit_number"), bedrooms: Number(formData.get("bedrooms") ?? 1), bathrooms: Number(formData.get("bathrooms") ?? 1), sq_ft: formData.get("sq_ft") ? Number(formData.get("sq_ft")) : undefined, rent_amount: Number(formData.get("rent_amount")), status, notes: formData.get("notes") || undefined, } const res = await fetch( isEditing ? `/api/units/${unit!.id}` : "/api/units", { method: isEditing ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), } ) setLoading(false) if (!res.ok) { const data = await res.json().catch(() => null) toast.error(data?.error ?? (isEditing ? "Failed to update unit" : "Failed to add unit")) return } toast.success(isEditing ? "Unit updated" : "Unit added") if (onSuccess) { onSuccess() } else { router.push(`/properties/${propertyId}`) router.refresh() } } const inputClass = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder:text-white/30 focus:outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500" const labelClass = "block text-sm font-medium text-white/70 mb-1.5" return (