"use client" import { useState } from "react" import { useRouter } from "next/navigation" import { toast } from "sonner" import { useWarnUnsaved } from "@/lib/hooks/use-warn-unsaved" import { Select } from "@/components/ui/select" import type { Tenant } from "@/types" interface TenantFormProps { properties: { id: string; name: string; units: { id: string; unit_number: string; status: string }[] }[] tenant?: Tenant } export function TenantForm({ properties, tenant }: TenantFormProps) { const router = useRouter() const [loading, setLoading] = useState(false) const [error, setError] = useState("") const [isDirty, setIsDirty] = useState(false) const [selectedPropertyId, setSelectedPropertyId] = useState(tenant?.property_id ?? "") useWarnUnsaved(isDirty) const propertyOptions = [ { value: "", label: "Select property…" }, ...properties.map((p) => ({ value: p.id, label: p.name })), ] const availableUnits = properties .find((p) => p.id === selectedPropertyId) ?.units.filter((u) => u.status === "vacant" || u.id === tenant?.unit_id) ?? [] const unitOptions = [ { value: "", label: "No unit assigned" }, ...availableUnits.map((u) => ({ value: u.id, label: `Unit ${u.unit_number}` })), ] async function handleSubmit(e: React.FormEvent) { e.preventDefault() setLoading(true) setError("") const formData = new FormData(e.currentTarget) const body: Record = { property_id: formData.get("property_id"), unit_id: formData.get("unit_id") || undefined, first_name: formData.get("first_name"), last_name: formData.get("last_name"), email: formData.get("email") || undefined, phone: formData.get("phone") || undefined, emergency_contact_name: formData.get("emergency_contact_name") || undefined, emergency_contact_phone: formData.get("emergency_contact_phone") || undefined, move_in_date: formData.get("move_in_date") || undefined, notes: formData.get("notes") || undefined, } const res = await fetch( tenant ? `/api/tenants/${tenant.id}` : "/api/tenants", { method: tenant ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } ) const data = await res.json() setLoading(false) if (!res.ok) { setError(typeof data.error === "string" ? data.error : "Something went wrong") return } setIsDirty(false) toast.success(tenant ? "Tenant updated" : "Tenant added") router.push(`/tenants/${data.id}`) router.refresh() } const cls = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-white/30 outline-none ring-indigo-500 transition focus:border-indigo-500/50 focus:ring-1" const lbl = "mb-1.5 block text-sm font-medium text-white/70" return (
setIsDirty(true)} className="space-y-5 rounded-xl border border-white/[0.06] bg-[#16161f] p-6"> {error && (
{error}
)}
{availableUnits.length === 0 && (

No vacant units in this property.

)}
)}

Emergency Contact